我需要一些帮助来理解我们试图在实体框架中解决的情况。
我们试图更新两个表1.映射表(两个外键= ProductId和anotherId) 2.在表中创建一个新记录(调用产品,生成的主键是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(); 返回为null,我假设这是因为事务没有提交。
如何克服这种情况?如何创建映射记录并使用新创建的Id?在同一个事务中运行多个保存会导致错误吗?
发布于 2015-12-18 18:00:34
您应该将product添加到上下文中以保存它:
context.Product.Add(product);
context.SaveChanges();此外,SaveChanges()返回已更改记录的计数,因此在保存后查看product.id以检索插入的记录id。
https://stackoverflow.com/questions/34361372
复制相似问题