2

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; set;}
}

I'm using stateless facades, wich means my DbContext is disposed right after recovering the objects and is created to store the new ones. Shouldn't it know that Classroom isn't a new object since it's ID is already in the DB? Using the debugger I can track to the point right before I call the SaveChanges method and Classroom.id is the one I have on the database. What's the problem? EF adds a new Classroom with the exact properties as the previous one, but with a new PK. What am I doing wrong here?

This is the code used for the general CRUD operations (They are in my DbContext) Both update and delete work just fine:

    public void Update(DbSet MySet, object Obj)
    {
        MySet.Attach(Obj);
        var Entry = this.Entry(Obj);
        Entry.State = EntityState.Modified;
        this.SaveChanges();
    }


    public void Insert(DbSet MySet, object Obj)
    {
        MySet.Add(Obj);
        this.SaveChanges();
    }


    public void Delete(DbSet MySet, object Obj)
    {
        MySet.Attach(Obj);
        var Entry = this.Entry(Obj);
        Entry.State = EntityState.Deleted;
        this.SaveChanges();
    }
croxy
  • 4,082
  • 9
  • 28
  • 46
Alvaro
  • 11,797
  • 9
  • 40
  • 57

1 Answers1

5

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.

Mark Oreta
  • 10,346
  • 1
  • 33
  • 36
  • Thanks, this might work! I was using similar code, but I had defined a general method to insert my entities, taking a generic object: public void Insert (DataSet dSet,object obj) { dSet.Add(obj); this.SaveChanges(); } So I guess there isn't a way to do it with this kind of anonymous state – Alvaro Oct 22 '12 at 02:10
  • it is adding foreign key but forcing insert... I want it just to keep the foreign key – RollRoll Apr 16 '16 at 19:18
  • 1
    Thanks, that work. this is annoying. If the model has an Id is expected that EF know that is not a new one. but thanks again. – jcmordan Jan 25 '17 at 03:24