我會向您介紹一些關於「真實交易」和「僞交易」的問題。 我認爲實體框架實現了僞事務,我會告訴你爲什麼。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