I have the following relationships between some types A, B, C and X:
A->B->X
|->C->X
|->X
Now assume that i want to add a new A to the database and associate it with existing instances of B, C and X.
What i’m doing is this:
using (Context context = new Context())
{
context.As.Attach(A);
context.As.Add(A);
context.SaveChanges();
}
It seems to work but i’m not sure about it since Attach is usually used to attach existing instances.
This alternative does not work:
using (Context context = new Context())
{
context.Bs.Attach(A.B);
context.Cs.Attach(A.C);
context.As.Add(A);
context.SaveChanges();
}
Because in this case X gets attached twice (A.B.X and A.C.X) and entity framework throws an exception:
System.InvalidOperationException:
An object with the same key already exists in the ObjectStateManager.
The ObjectStateManager cannot track multiple objects with the same key.
Does it make sense to use my solution or is there a better way to do this?
Yes your solution makes sense – you have attached whole graph and changed just
AtoAddedstate. It can be also rewritten as:In some complex scenarios it can be also useful to do that in reverse order – add all and change state of all existing items.