【问题标题】:Retrieve Identity value in entity framework and still able to rollback在实体框架中检索身份值并且仍然能够回滚
【发布时间】:2011-07-29 16:33:55
【问题描述】:
我想在使用实体框架在 DB 中插入一行后检索 Identity 列值。所以我必须调用context.savechanges(),但是如果更新行并检索标识列值后出现问题,我想完全回滚。
这在 EF 4.0 中可能吗?
我知道如何检索标识列值,并且通过回滚,我的意思是应该删除插入的行。
我的标识列是自动生成的 bigint 类型。
【问题讨论】:
标签:
entity-framework-4
transactions
rollback
【解决方案1】:
用TransactionScope怎么样
using (var scope = new TransactionScope())
{
using (var context = new MyContext())
{
// Insert data
context.SaveChanges();
// Do something with retrieved Id
}
// If something goes wrong and following command is not called
// transaction will rollback
scope.Complete(); // Commit
}
如果不调用Complete,事务会回滚。