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

前端 未结 2 1780
星月不相逢
星月不相逢 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 03:18

    in case of ef-core

    Attach is good for cases when you are adding a new entity to the database with navigational properties. Attach only marks newly created items as changed.

    Let's say you are adding a new Employee to an Industry. If the industry already exists in the database it must have an ID. and the Employee you are adding is not inserted to the database yet so it does not have an ID yet (I am talking about row IDs here).

    So what attach does is since the Industry already has an ID. Attach marks that as Unchanged. And your Employee who doesn't have an ID yet attach marks it as Added.

    You can read more about this topic here: https://www.learnentityframeworkcore.com/dbcontext/modifying-data#attach

提交回复
热议问题