一组业务整体处理的行为叫一个事务。这一组的业务都能成功处理,我们就可以把这个事务提交来保存你已做的行为结果。事物的Commit是执行了你的方法进行了数据库的提交,之前的sava都是放在缓存中并没有执行到数据库。
- 1. 使用TransactionScope
这个写法最像ado.net的事务提交。需要引用System.Transactions命名空间。
var invoiceDetailOriginal = InvoiceDetailService.Query(m => m.DetailID == 86).FirstOrDefault(); using (TransactionScope transaction = new TransactionScope()) { try { List<BL_Invoice> invoiceLst = new List<BL_Invoice>(); List<BL_InvoiceDetail> detailLst = new List<BL_InvoiceDetail>(); var lst = InvoiceService.Query(m => m.ID > 49).ToList(); for (int n = 0; n < 3; n++) { BL_Invoice i = new BL_Invoice() { IsWD = lst[n].IsWD, IsAzure = lst[n].IsAzure, InvoiceNumber = lst[n].InvoiceNumber, InvoiceDate = DateTime.Now, BITTYPE = lst[n].BITTYPE, BPexternalID = lst[n].BPexternalID, CAexternalID = lst[n].CAexternalID, Amount = lst[n].Amount, IsMETHODSynced = false, METHOD_INCC = (n == 1) ? "XXXX" : "P", CreatedDate = DateTime.Now }; BL_InvoiceDetail d = new BL_InvoiceDetail() { BL_Invoice = i, BITREF32 = invoiceDetailOriginal.BITREF32, MSSKU = (n == 1) ? "存二十个汉字;存二十个汉字;存二十个汉字;存二十个汉字;存二十个汉字。" : invoiceDetailOriginal.MSSKU, Amount = invoiceDetailOriginal.Amount, Tax = invoiceDetailOriginal.Tax, DeferralAmount = invoiceDetailOriginal.DeferralAmount, BITDATE_FROM = invoiceDetailOriginal.BITDATE_FROM, BITDATE_TO = invoiceDetailOriginal.BITDATE_TO, CreatedDate = DateTime.Now }; InvoiceService.Add(i); InvoiceDetailService.Add(d); //到这一步出错,然后看添加invoice也没有添加上。 这就是事务的作用。当然entity的savaChangge() 也可以看做是一个事务。 transaction.Complete(); } } catch (Exception ex) { throw ex; } finally { transaction.Dispose(); }
- 2. SaveChangges() 和UnitOfWork.Commit()
插入一两个相关的list。list中有一条出错,整个事务回滚。利用的 reponsitory的 IUnitOfWork。
List<BL_Invoice> invoiceLst = new List<BL_Invoice>(); List<BL_InvoiceDetail> detailLst = new List<BL_InvoiceDetail>(); var lst = InvoiceService.Query(m => m.ID > 49).ToList(); for (int n = 0; n < lst.Count();n++) { BL_Invoice i = new BL_Invoice() { IsWD = lst[n].IsWD, IsAzure = lst[n].IsAzure, InvoiceNumber = lst[n].InvoiceNumber, InvoiceDate = DateTime.Now, BITTYPE = lst[n].BITTYPE, BPexternalID = lst[n].BPexternalID, CAexternalID = lst[n].CAexternalID, Amount = lst[n].Amount, IsMETHODSynced = false, METHOD_INCC =(n==1)?"XXX":"P", CreatedDate = DateTime.Now }; invoiceLst.Add(i); var invoiceDetailOriginal = InvoiceDetailService.Query(m => m.DetailID == 86).FirstOrDefault();//lst[n].BL_InvoiceDetail.FirstOrDefault(); BL_InvoiceDetail d = new BL_InvoiceDetail() { BL_Invoice = i, BITREF32 = invoiceDetailOriginal.BITREF32, MSSKU = (n == 1) ? "存二十个汉字;存二十个汉字;存二十个汉字;存二十个汉字;存二十个汉字。" : invoiceDetailOriginal.MSSKU, Amount = invoiceDetailOriginal.Amount, Tax = invoiceDetailOriginal.Tax, DeferralAmount = invoiceDetailOriginal.DeferralAmount, BITDATE_FROM = invoiceDetailOriginal.BITDATE_FROM, BITDATE_TO = invoiceDetailOriginal.BITDATE_TO, CreatedDate = DateTime.Now }; detailLst.Add(d); } InvoiceService.AddRange(invoiceLst, detailLst);
总体来说Entity Framework中的数据库操作无不体现着事务的关联性,毕竟这也是合理的要求。比ado.net中操作简单方便。