我正在实现一个服务层,我需要确保跨多个表的特定数量的操作发生在事务中。这是工作流程。如何获取DbContext尚未保存的插入记录的可见性
- 我得到一个需要存储在HistoricalData表中的HistoricalData对象的实例。这是在AddHistoricalData方法中完成的。
- 我需要从HistoricalData表中检索所有记录,包括#1中插入的内容,但可以有更多记录。这在ProcessAllData方法中完成。
- 处理所有这些记录后,结果存储在另外两个表中,即ProcessStatus和ProcessResults。如果出现任何问题,我需要回滚事务,包括在操作#1中插入的内容。
这是如何实施的。
public class HistoricalDataService : IHistoricalDataService
{
private MyDbContext dbContext;
public HistoricalDataService(MyDbContext context)
{
this.dbContext = context;
}
void AddHistoricalData(HistoricalData hData)
{
// insert into HistoricalData table
}
void ProcessAllData()
{
// Here we process all records from HistoricalData table insert porcessing results into two other tables
}
void SaveData()
{
this.dbContext.SaveChanges();
}
}
这里是如何调用这个类的方法。
HistoricalDataService service = new HistoricalDataService (dbcontext);
service.AddHistoricalData(HistoricalData instance);
service.ProcessAllData();
service.SaveData();
问题这种方法是,无论是调用AddHistoricalData方法时插入HistoricalData表是不是在ProcessAllData呼叫可见,因为dbContext.SaveChanges只在最后调用。我在想,我需要以某种方式将事务范围引入此处,但不知道如何在应该启动该事务范围的位置公开一个函数?
你为什么说HistoricalData不可见?如果您将HistoricalData对象插入到dbContext.HistoricalData中,那么您应该能够在ProcessAllData方法中获得此对象 – taquion
不知道为什么,但使用context.HistoricalData插入AddHistoricalData方法的位置。添加仅在Context.HistoricalData集合中的ProcessAllData方法中可见。我的猜测是我必须在上下文中调用SaveChanges –