【问题标题】:Entity Framework 6- Saving data in a transaction实体框架 6- 在事务中保存数据
【发布时间】: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


    【解决方案1】:

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

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

    同样SaveChanges()返回更改记录的计数,所以在保存后查看product.id检索插入的记录ID。

    【讨论】:

    • 谢谢哥们...我正在将产品添加到上下文中,但我认为我的脑袋都被淹没了,我期待保存返回 ID 并没有意识到这一点。我的数据还有另一个问题,我的表只有外键,而实体框架将其视为视图,不让我更新它......这是有道理的......我无论如何都需要将主键添加到我的映射中,这实际上修好了。
    • @fireholster,没问题!如果数据没有唯一标识符,即使调用视图,EF 也可能无法正常工作。此链接可能会有所帮助:girlfromoutofthisworld.com/…
    猜你喜欢
    • 1970-01-01
    • 2014-06-07
    • 1970-01-01
    • 2016-07-18
    • 2022-12-03
    • 2017-12-10
    • 2014-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多