.net EF 事物 订单流水号的生成 (一)
首先需要 添加 System.Transactions 程序集
数据表:
create table SalesOrder ( ID int identity(1,1) primary key not null, OrderNo nvarchar(50) not null, OrderDate datetime not null, UserName nvarchar(50) not null ) create table FlowNo ( ID int identity(1,1) primary key not null, OrderNo nvarchar(50) not null, OrderType nvarchar(50) not null, Remark nvarchar(50) not null ) insert FlowNo values ('SM160309-00001','SM','销售订单')
控制台测试程序。
测试的时候 ,可以 输入 userName ,最大字符为50,可以测试 输入50个字符以上的用户名,会发现
var tempModel = db.SalesOrder.FirstOrDefault(); if (tempModel != null) tempModel.UserName = tempModel.UserName + orderNo.ToString().PadLeft(5, '0'); db.SaveChanges();
这段代码 没有 效果了。虽然是后面的代码报错,第一行的数据不会发生改变。
using System; using System.Linq; using System.Transactions; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { try { using (var tran = new TransactionScope()) { using (var db = new pengbgDBEntities()) { var flowNo = db.FlowNo.FirstOrDefault(x => x.OrderType == "SM"); if (flowNo != null) { var orderNo = int.Parse(flowNo.OrderNo.Split('-')[1]) + 1; string newOrderNo; if (flowNo.OrderNo.Split('-')[0] != "SM" + DateTime.Now.ToString("yyMMdd")) { newOrderNo = "SM" + DateTime.Now.ToString("yyMMdd-") + 1.ToString().PadLeft(5, '0'); } else { newOrderNo = "SM" + DateTime.Now.ToString("yyMMdd-") + orderNo.ToString().PadLeft(5, '0'); } var userName = Console.ReadLine(); var tempModel = db.SalesOrder.FirstOrDefault(); if (tempModel != null) tempModel.UserName = tempModel.UserName + orderNo.ToString().PadLeft(5, '0'); db.SaveChanges(); db.SalesOrder.Add(new SalesOrder { OrderDate = DateTime.Now, OrderNo = newOrderNo, UserName = userName }); db.SaveChanges(); flowNo.OrderNo = newOrderNo; db.SaveChanges(); } } tran.Complete(); Console.WriteLine("操作成功"); } } catch (Exception exception) { Console.WriteLine(exception.Message); } finally { Console.WriteLine("按任意键继续"); Console.ReadKey(); } } } }