实体框架6-在事务中保存数据

时间:2015-12-18 17:57:42

标签: c# asp.net-web-api entity-framework-6

我需要一些帮助来理解我们试图在实体框架中解决的情况。

我们正在尝试更新两个表 1.映射表(两个外键= ProductId和anotherId) 2.在表中创建新记录(在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(); 

返回null,我假设是由于事务未提交。

如何克服这种情况? 如何创建映射记录并使用新创建的Id? 在同一事务中运行多个保存会导致错误吗?

1 个答案:

答案 0 :(得分:2)

您应该将product添加到上下文中以保存它:

context.Product.Add(product);
context.SaveChanges();

同样SaveChanges()会返回已更改记录的数量,因此请在保存后查看product.id以检索插入的记录ID。