What is the difference between IDbSet.Add and DbEntityEntry.State = EntityState.Added?

后端 未结 2 1225
遇见更好的自我
遇见更好的自我 2020-12-03 05:30

In EF 4.1+, is there a difference between these 2 lines of code?

dbContext.SomeEntitySet.Add(entityInstance);
dbContext.Entry(entityInstance).State = EntityS         


        
相关标签:
2条回答
  • 2020-12-03 05:53

    When you use dbContext.SomeEntitySet.Add(entityInstance); the status for this and all its related entities/collections is set to added, while dbContext.Entry(entityInstance).State = EntityState.Added; adds also all the related entities/collections to the context but leaves them as unmodified. So if the entity that you are trying to create has a related entity (and it's value its not null), when you use Add it will create a new object for that child entity, while with the other way it won't.

    0 讨论(0)
  • 2020-12-03 06:07

    I just tested this with EF 6, with related entities/navigation properties, and in both cases the created objects were identical. (All parent and related child objects were created.) The only difference I noticed was that Add was faster by about a factor of 2. My data had 1000 parent objects, each with 5 child objects for a total of 6000 objects written to the DB.

    0 讨论(0)
提交回复
热议问题