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

Viewed 687

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?

1 Answers

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

Related