简体   繁体   中英

C# Entity Framework: Insert Child Entity and Update Parent, One Transaction

How do I add a new child record in Entity Framework and update the ParentId reference key?

We have an Employee and a ProductSales table.

The Employee table contains column of most recent ProductSaleId .

If I add a new entry to ProductSale , it will acquire a new identity column in the SQL Server database.

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

Now updating the Employee table reference key like this:

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

We know the EmployeeId which is 5. However, this takes two transactions from two save operations.

I want to this to be done in one transaction. How can this be completed?

Using EF Core 3.1, Entities are scaffolded with foreign keys

Resource:

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

Entity Framework automatic scaffold was setup. So the following worked, Instead of using employee.ProductSaleId , just use ProductSale , and update the Parent directly.

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

Entity Framework Core will automatically adjust with Insert or Update

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM