EF5 incrementing Unique ID without calling savechanges until user request to save

谁说胖子不能爱 提交于 2019-12-11 12:47:21

问题


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).



来源:https://stackoverflow.com/questions/11931034/ef5-incrementing-unique-id-without-calling-savechanges-until-user-request-to-sav

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!