且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

何时使用DbSet< T>。新增()VS DbSet< T> .Attach()

更新时间:2022-03-13 15:02:59

那么,当你使用连接你告诉该实体是已经在数据库的背景下,的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.

这就是区别。