【发布时间】:2015-12-18 17:57:41
【问题描述】:
我需要一些帮助来理解我们试图在实体框架中解决的情况。
我们正在尝试更新两个表 1.映射表(两个外键=ProductId和anotherId) 2.在Table中新建一条记录(在Product中调用,生成的主键为productId)
我们要确保产品表和映射表都成功更新,否则事务角色返回。
我们使用单个交易作为
using (var context = new SomeContext())
{
using (var dbContextTransaction = context.Database.BeginTransaction())
{
try
{ //Create the record to be saved
var product = new Product{ // set the data}
var newProductId = context.SaveChanges();
//Update the Mapping Table
var anotherData = context.AnotherTable.where(x => x.id = anotherId).FirstOrDefault();
var productData = context.Product.where(x => x.id = newProductId).FirstOrDefault();
//Create the Mapping Table record
productData.AnotherDatas.Add(anotherData);
context.SavceChanges();
dbContextTransaction.Commit();
}
catch (Exception)
{
dbContextTransaction.Rollback();
}
}
}
但问题是
var productData = context.Product.where(x => x.id = newProductId).FirstOrDefault();
返回为空,我假设这是由于事务未提交。
如何克服这种情况? 如何创建映射记录并使用新创建的 Id? 在同一个事务中运行多个保存会导致错误吗?
【问题讨论】:
标签: c# asp.net-web-api entity-framework-6