I\'ve read some questions/answers that have to do with this particular error message, but I\'m not quite understanding the appropriate solution.
I\'ve read many time
You should get a reference to the child and owner objects in the same context. An approach for this would be to get the ids and then pass them as parameters to the AssociateAndSave(int oId, int cId)
method.
Then, you retrieve the references to the objects in the same context and you make the attachment.
private static void Main(string[] args)
{
DeleteAllEntities();
CreateInitialEntities();
int oId = LoadOwnerId();
int cId = LoadChildId();
AssociateAndSave(oId, cId);
}
private static int LoadOwnerId()
{
using (var context = new ModelEntities())
{
return (from o in context.Owners
select o).First().Id;
}
}
private static int LoadChildId()
{
using (var context = new ModelEntities())
{
return (from c in context.Children
select c).First().Id;
}
}
private static void AssociateAndSave(int oId, int cId)
{
using (var context = new ModelEntities())
{
var owner = (from o in context.Owners
select o).FirstOrDefault(o => o.ID == oId);
var child = (from o in context.Children
select o).FirstOrDefault(c => c.ID == cId);
owner.Children.Add(child);
context.Attach(owner);
context.SaveChanges();
}
}
You cannot delete objects from one context, with an instance of another context, because each context tracks its objects separately.
One ideea would be to provide each of your methods a parameter of your context type so your operations are made within the same context.
EX:
private static void CrudOperationExample(DBContext contextInstane)
{
//perform crud operations.
}
I you want to do it more nicely, i suggest you look for dependency injection, as it is very much helpful in ORM's .