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
-
1Use auto-incremented columns and EF will handle it for you. – Ladislav Mrnka Aug 13 '12 at 09:03
-
Hi, I reversed engineered code first from an existing DB, the DB Table column ID is set as identity increment , but where in the table class do you specify auto-increment option or attribute – Pieter Prinsloo Aug 13 '12 at 09:13
-
You will not - that is default for integer keys but values in application are not auto-incremented they are set only after saving changes. – Ladislav Mrnka Aug 13 '12 at 09:15
-
then how will one work in a scenario where a user add a record, then add child records for the parent record where the parent record is the foreign key on the child record and then start by adding a new parent record and then the child records again, in an application where the users work with transactions only committing when finished adding all the data – Pieter Prinsloo Aug 13 '12 at 09:24
2 Answers
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.

- 1
- 1

- 360,892
- 59
- 660
- 670
-
can you please link me the documentation from where you got this information please? – michelle Sep 23 '13 at 13:03
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).

- 105,341
- 31
- 202
- 291