Can Entity Framework add many related entities with single SaveChanges()?

前端 未结 3 509
灰色年华
灰色年华 2020-12-19 02:32

I am writing many (20+) parent child datasets to the database, and EF is requiring me to savechanges between each set, without which it complains about not being able to fig

3条回答
  •  無奈伤痛
    2020-12-19 03:22

    Since they're all new items rather than

    itemTrackingID = addItemTracking.ItemTrackingID,
    

    you could go with

    addItemTracking.InventoryTransaction = addInventoryTransaction;
    

    (or whatever the associated navigation property is) and pull the _context.SaveChanges() out of the loop entirely. Entity Framework is very good at inserting object graphs when everything is new. When saving object graphs containing both new and existing items setting the associated id is always safer.

提交回复
热议问题