Reputation: 1945
public class Parent
{
public int ID;
public string Name;
public int Child_ID;
public Child Child;
}
public class Child
{
public int ID;
public string Name;
public int Parent_ID;
public Parent Parent;
}
I have a little issue with ef when it comes to the folowing scenario:
I added a parent with a child but if I extract a Child c
(with c.Parent == null
) and then it's Parent p
(2 queries) and then do:
Child.Parent = p;
context.SaveChanges();
It will add a new Parent
in the database even if p
exists. Is there a way to override this behavior?
Upvotes: 1
Views: 54
Reputation: 39376
Probably you are working with a detached entity. If you don't get the parent entity from the same instance of your constext, when you assign the Parent
to the Child
instance, EF considers this to be an unrecognized entity and its default behavior for unrecognized entities with no state is to mark them as Added
. So, again, the Parent
will be inserted into the database when SaveChanges
is called.
To resolve that problem, try this:
context.Parents.Attach(p);
Child.Parent = p;
context.SaveChanges();
Alternatively, in place of context.Parents.Attach(p)
, you could set the state of the Parent
before or after the fact, explicitly setting its state to Unchanged
:
context.Entry(p).State = EntityState.Unchanged;
If you want to learn more about this topic, I suggest you read this article
Upvotes: 2