我会向您介绍一些关于“真实交易”和“伪交易”的问题。 我认为实体框架实现了伪事务,我会告诉你为什么。UnitOfWork - 真实交易
// Partial Code
// *** Transaction scenario *** //
ObjectContext ctx = new ...
ctx.Connection.Open();
using(var t = ctx.Connection.BeginTransaction())
{
var invoice = new invoice{ price=10, Customer="myClient"};
ctx.CreateObjectSet<invoice>().AddObject(invoice);
ctx.SaveChanges();
// here I 've the ID invoice (I mean it like identity autoincrement) and I can execute some business logic basis on ID value
var client = new client { Name="Robert", Address="some address", IdInvoice=invoice.ID}
ctx.CreateObjectSet<client>().AddObject(client);
ctx.SaveChanges();
// Persistence
t.Commit(); // some error? t.Rollback
}
// *** PSEUDO Transaction scenario *** //
ObjectContext ctx = new ...
var invoice = new invoice{ price=10, Customer="myClient"};
ctx.CreateObjectSet<invoice>().AddObject(invoice);
// here I haven't invoice ID (I mean it like identity autoincrement) and I CANNOT EXECUTE ANY business logic basis on ID value
var client = new client { Name="Robert", Address="some address", IdInvoice=invoice.ID} // BAD: its value is zero
ctx.CreateObjectSet<client>().AddObject(client);
// Persistence
ctx.SaveChanges();
注意,EF将更新ID值被称为唯一的SaveChanges之后且仅当存在发票和客户对象之间的关系,否则什么也不会正常工作。
所以,我的问题是:在unitOwWork模式中使用“真正的事务”是否是一个好习惯? 为什么EF让我们有可能偶然发现像我向你展示过的那个问题?
完美..非常感谢你 – bit