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?