我需要在EF中的事务回滚后写入日志表。 目前的代码:
using (MyDataBase db = new DataBase())
{
using (var dbContextTransaction = db.Database.BeginTransaction())
{
try
{
//Inserting several records to different tables
var newEntity = new Entity();
...
db.Entity.Add(newEntity);
db.SaveChanges();
db.up_StoredProcCall;
dbContextTransaction.Commit();
}
catch (Exception ex)
{
dbContextTransaction.Rollback();
var logEntry = new LogEntry();
...
db.LogEntry.Add(logEntry);
db.SaveChanges();
}
}
}
它不起作用,因为EF在内部缓存所有插入并在单个事务中刷新所有以及日志记录:
db.LogEntry.Add(logEntry);
db.SaveChanges();
达成目标的最佳方法是什么:
答案 0 :(得分:1)
使用失败的SaveChanges()关闭DbContext并从新的日志条目中写入日志条目。 AFAIK无法放弃DbContext中的挂起更改。
例如
using (MyDataBase db = new DataBase())
{
using (var dbContextTransaction = db.Database.BeginTransaction())
{
try
{
//Inserting several records to different tables
var newEntity = new Entity();
...
db.Entity.Add(newEntity);
db.SaveChanges();
db.up_StoredProcCall;
dbContextTransaction.Commit();
}
catch (Exception ex)
{
dbContextTransaction.Rollback();
db.Dispose();
using (MyDataBase dbLog = new DataBase())
{
var logEntry = new LogEntry();
...
dbLog.LogEntry.Add(logEntry);
dbLog.SaveChanges();
}
}
}
}