我一直使用添加(),跑进其中,由母公司正在复制数据库的时候添加问题 ING一个孩子。使用附加()解决了这个,但我想知道为什么,而不是盲目地跌跌撞撞各地。
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.
推荐答案那么,当你使用连接你告诉该实体是已经在数据库的背景下,的SaveChanges 将拥有附加的实体没有影响。 添加,在另一方面,改变了实体的状态在上下文(如果它已经存在)为添加 ,这意味着它将总是插入的实体,当你调用数据库的SaveChanges 。
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.
这就是区别。
更多推荐
何时使用DbSet< T>。新增()VS DbSet< T> .Attach()
发布评论