【发布时间】:2016-12-30 15:44:37
【问题描述】:
我正在实现一个服务层,我需要确保跨多个表的特定数量的操作发生在一个事务中。这是工作流程。
- 我得到了一个 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 方法中获取此对象
-
不知道为什么,但是使用 context.HistoricalData.Add 在 AddHistoricalData 方法中插入的位置在 context.HistoricalData 集合中的 ProcessAllData 方法中可见。我的猜测是我必须在上下文中调用 SaveChanges
标签: c# transactions entity-framework-6 dbcontext service-layer