The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects

后端 未结 2 1405
终归单人心
终归单人心 2020-12-05 23:54

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

相关标签:
2条回答
  • 2020-12-06 00:06

    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();
        }
    }
    
    0 讨论(0)
  • 2020-12-06 00:20

    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 .

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