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

前端 未结 2 1783
星月不相逢
星月不相逢 2021-02-05 02:22

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()<

2条回答
  •  灰色年华
    2021-02-05 02:59

    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.

提交回复
热议问题