How can I prevent EF from inserting an object that already exists in the db when adding one that contains this first one?

后端 未结 1 956
梦谈多话
梦谈多话 2021-01-22 08:58

It\'s quite self-explainatory. I have a class that contains another Let\'s call them Subject and Classroom

public class Subject
{
   public Classroom Class {get;         


        
1条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-22 09:10

    Without seeing you're actual code on how you're either updating or creating your Subject entity, it's hard to tell. However, you're probably not attaching the Classroom so EF is assuming that the entity is new, when it's really not.

         using (Model m = new Model())
         {
            m.Subject.Add(subject);
            m.Classrooms.Attach(subject.Class);
            m.SaveChanges();           
         }
    

    Even though the PK is the same, without attaching to the Context, EF has no way of figuring out what you're intention is. Attaching the entity explicitly tells your context what you want.

    0 讨论(0)
提交回复
热议问题