EF5 incrementing Unique ID without calling savecha

2019-07-26 22:20发布

问题:

How do one add multiple items to a table and child tables based on the parent table unique id in child table without calling save changes every time you add a row, only when the user click on the save button changes must be committed

回答1:

It depends on the way how you defined your entities. If you are using independent associations it will simply work.

If you are using foreign key associations you will have to use temporary keys for principal entities and set them to foreign key properties in dependent entities. These temporary keys in parent must be unique (use for example negative values) and EF will automatically replace them with real values when saving changes.



回答2:

Entity Framework first inserts parent records and uses their auto-incremented identity values to set any foreign key values of children. EF can do that because SQL server increments identity columns within the scope of a transaction, so the new values are assigned while the transaction is not yet committed. (A new insert after a roll-back reveals that the identity column misses the values that were assigned in the rolled-back transaction).

So it is no problem to do something like

var cust = new Customer { ... };
context.Customers.AddObject(cust); // (or Add() with DbContext).
var ord = new Order  { ... };
ord.OrderLines.Add(new OrderLine  { ... });
cust.Orders.Add(ord);
context.SaveChanges();

where ... is a placeholder for setting properties (no parent id's).