17

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

dbContext.SomeEntitySet.Add(entityInstance);
dbContext.Entry(entityInstance).State = EntityState.Added;

Or do they do the same thing? I'm wondering if one might affect child collections / navigation properties differently than the other.

danludwig
  • 46,965
  • 25
  • 159
  • 237

2 Answers2

21

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.

fbiagi
  • 766
  • 6
  • 11
  • and does this also apply to EntityState.Deleted & EntityState.Changed? – John John Oct 31 '14 at 16:52
  • I believe you refer to dbContext.Entry(entityInstance).State, in that case I think yes, as the Entity method only adds it to the graph with out changing its state (unmodified) and then you manually change the state of only that entity, not its related ones. – fbiagi Nov 03 '14 at 13:32
  • Have you seen the comment from @MikeBrind on the other question? – Colin Nov 04 '14 at 14:12
  • Yes, and I still think this is the right answer. I figured this out while solving a bug that identicall entities were being added to the db when storing a related entity on a web service. if you look at the remarks on the .Add docs (http://msdn.microsoft.com/en-us/library/gg679587%28v=vs.113%29.aspx) you'll see this, but there is no mention on the .Entry method. If you have doubts the best way to clear them will be to make a proof of concept test. – fbiagi Nov 04 '14 at 15:14
  • 6
    Sorry, but this isn't true (for EF 6, but I think for any version since `DbSet` was introduced). Both methods mark *all* entities in the object graph as `Added` *if these entries are not yet attached to the context*. So it's not the adding method that matters, but the state of the child entities before adding the root entity. – Gert Arnold Jul 24 '15 at 21:39
1

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.

TTT
  • 22,611
  • 8
  • 63
  • 69