【问题标题】:C# Entity Framework: Insert Child Entity and Update Parent, One TransactionC# 实体框架:插入子实体并更新父实体,一个事务
【发布时间】:2020-12-10 06:54:18
【问题描述】:

如何在 Entity Framework 中添加新的子记录并更新 ParentId 引用键?

我们有一个Employee 和一个ProductSales 表。

Employee 表包含最近的ProductSaleId 列。

如果我向ProductSale 添加一个新条目,它将在 SQL Server 数据库中获取一个新的标识列。

lastProductSale = new ProductSale { Product = "Furniture", Amount= 1000, EmployeeId = 5};
_dbContext.Add(productSale);
_dbContext.SaveChanges();
int lastProductSaleId = lastProductSale.productSaleId;

现在像这样更新Employee 表引用键:

employee.ProductSaleId = lastProductSaleId;
_dbContext.SaveChanges();

我们知道EmployeeId 是 5。但是,这需要来自两个保存操作的两个事务。

我希望在一笔交易中完成。如何完成?

使用 EF Core 3.1, 实体是用外键搭建的

资源:

How can I retrieve Id of inserted entity using Entity framework?

【问题讨论】:

  • 嗨 @devlincarnate 是的,我在 DB 和 EF 中有一个外键设置
  • 哦等等... LastProductSaleId 只是最近售出产品的ID。对不起,我误解了这种关系。据我所知,您必须进行 2 次保存。但是,您可以使用TransactionScope 来管理一次保存失败的情况。
  • 请注意,这是一个有问题的数据库设计。你应该避免存储LastProductSaleId,除非你绝对知道,因为你试过了,按需计算太慢了。
  • 是的,这个数据库设计有问题。您不需要员工表中的 LastProductSaleId。每当您想显示员工的最新销售时,然后使用employeeid + date 获取最新的销售数据。无论如何,如果您想要一笔交易,那是不可能的,因为您需要使用 savechanges 才能获得新的 id。
  • 嗨 @Asherguru 我同意,我告诉 db 架构师,只是在做我的工作,但问题更具概念性,在一个事务中插入子项并更新父项

标签: c# .net linq .net-core entity-framework-core


【解决方案1】:

设置了实体框架自动脚手架。 所以以下工作, 不用employee.ProductSaleId,直接用ProductSale,直接更新Parent。

productSale = new ProductSale { Product = "Furniture", Amount= 1000, EmployeeId = 5};
employee.ProductSale = productSale;
_dbContext.SaveChanges();

Entity Framework Core 将通过插入或更新自动调整

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-19
    • 1970-01-01
    相关资源
    最近更新 更多