When to use DbSet.Add() vs DbSet.Attach()

asp.net-mvc c# entity-framework

Question

I have been using Add() and ran into a problem where by a parent entity was being duplicated in the database when Adding a child. Using Attach() solved this but I would like to know why rather than blindly stumbling around.

1
29
1/11/2016 9:11:06 AM

Accepted Answer

Well, when you use Attach you tell the context that the entity is already in the database, SaveChanges will have no effect over attached entities. Add, on the other hand, changes the state of the entity in the context (if it's already there) to Added, meaning it will always insert the entity in the database when you call SaveChanges.

That's the difference.

32
4/11/2013 2:19:57 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow