Search code examples
entity-framework-6logicdbcontextinsert-update

When and why to insert Entity and its relational Entity references


i am building a function for a bulk import from a file and i am asking myself what i should do, i would like some feedback and maybe learn certain things for the future.

I have 3 Entities, lets call them E1, E2 & E3.

E1 has a property E2 and E2 has a property E3. I can build everything up (doing checks and so on) and insert E3, which will insert E1 & E2 (IF they don't already exist of course otherwise i would attach them).

But why shouldn't i for example build up E1 and insert it, continue build E2 and insert it, lastly build up E3 (with E1 & E2) and insert it ?

Is there a specific reason i shouldn't do that, to many calls maybe, is it a "no-go", ... ?

Kind regards!


Solution

  • The most important thing is to call SaveChanges on the Context at the very end, when all entities are added. This way, all entities are inserted/updated in one Transaction and there are as few database-calls as possible. The benefits are good performance and atomic-Transactions ( all succeeds or all fails).