.net EF 事物 订单流水号的生成 (二):观察者模式、事物、EF

  针对.net EF 事物 订单流水号的生成 (一)  的封装。

  数据依然不变。

 

using System;
using System.Linq;
using System.Transactions;

namespace ConsoleApplication1
{
    class Program
    {
        static pengbgDBEntities db = new pengbgDBEntities();
        static void Main(string[] args)
        {
            try
            {
                DAL dal = new DAL();
                dal.AddOrder += dal_AddOrder;
                var newOrderNo = dal.Tran(DAL.EnumOrderType.SM);
                Console.WriteLine("添加成功:" + newOrderNo);
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.Message);
            }
            finally
            {
                Console.WriteLine("按任意键继续");
                Console.ReadKey();
            }
        }

        static int dal_AddOrder(string orderNo)
        {
            db.SalesOrder.Add(new SalesOrder() { UserName = Console.ReadLine(), OrderNo = orderNo, OrderDate = DateTime.Now });
            return db.SaveChanges();
        }
    }

    public class DAL
    {
        public delegate int DelTranOrder(string orderNo);
        public event DelTranOrder AddOrder;
        public pengbgDBEntities db = new pengbgDBEntities();

        public int Add(string orderNo)
        {
            return AddOrder(orderNo);
        }

        public string BulidOrderNo(EnumOrderType enunType)
        {
            var orderType = enunType.ToString();
            var flowNo = db.FlowNo.FirstOrDefault(x => x.OrderType == orderType);
            var flowNoStart = DateTime.Now.ToString("yyMMdd-");
            var flowNoEnd = "1";
            if (flowNo != null)
            {
                if (flowNo.OrderNo.Split('-')[0] != orderType + flowNoStart)
                {
                    flowNoEnd = (int.Parse(flowNo.OrderNo.Split('-')[1]) + 1).ToString();
                }
            }
            else
            {
                db.FlowNo.Add(new FlowNo { OrderNo = flowNoStart + flowNoEnd.PadLeft(5, '0'), OrderType = orderType, Remark = "New" });
            }
            return orderType + flowNoStart + flowNoEnd.PadLeft(5, '0');
        }

        public string Tran(EnumOrderType orderType)
        {
            var newOrderType = BulidOrderNo(orderType);
            using (var scope = new TransactionScope())
            {
                AddOrder(newOrderType);
                var flowNo = db.FlowNo.FirstOrDefault(x => x.OrderType == orderType.ToString());
                if (flowNo != null)
                    flowNo.OrderNo = newOrderType;
                db.SaveChanges();
                scope.Complete();
            }
            return newOrderType;
        }

        public enum EnumOrderType
        {
            SM,//销售订单
            PM // 外发订单
            //......其他
        }
    }
}

 

posted @ 2016-03-09 14:46  pengbg  阅读(712)  评论(1编辑  收藏