我会向您展示有关“真实交易”和“伪交易”的一些信息。我认为实体框架实现了一个伪事务,我会告诉你为什么。
// 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 仅在调用 SaveChanges 并且仅当发票和客户端对象之间存在关系时才会更新 ID 值,否则将无法正常工作。
所以,我的问题是:在 unitOwWork 模式上使用“真实交易”是一种好习惯吗?为什么 EF 让我们有可能偶然发现像我向您展示的那样的坏问题?