简体   繁体   中英

Entity Framework - “The relationship between the two objects cannot be defined” error, but I think I'm using the same context

In my ViewModel I have some code like that:

public class OrderViewModel
{
    private UserOrder order;
    private DeliveryCentre deliveryCentre;

    // This is my EF Container
    private CatalogueContainer catalogue = new CatalogueContainer();

    // do some stuff...

    public void Save()
    {
        if (order == null)
        {
            order = catalogue.UserOrders.CreateObject();
        }
        // do some other stuff...

         if ((deliveryCentre == null)
            || (deliveryCentre.Id != deliveryCentreId))
        {
           deliveryCentre = catalogue.DeliveryCentres.First(centre => centre.Id == deliveryCentreId);

            //Causes a context error, not sure why...
            order.DeliveryCentre= deliveryCentre;
        }

        catalogue.SaveChanges();

    }

So when the delivery centre is new and the order is new, I am hit by the old "The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects" error, which seems a trifle unfair to me - I just can't figure out what I need to do to make them belong more to the same object context. I assume this is due to some fundamental misunderstanding of the behaviour of Entity Framework.

You are not disposing your context. It may be possible that one of the entities order or deliveryCentre is attached to an old context which still holds references to the entities. You can create and dispose your context with an using statement inside of the Save method instead to using it as a member variable:

public void Save()
{
    using (var catalogue = new CatalogueContainer())
    {
        // your code...
    }
}

And remove the private catalogue member.

The solution turned out to only be indirectly related to the error message- @Slauma asked about the //do stuff... placeholders and when I commented those out the error disappeared.

It turned out that there was another relationship there, where I was creating the object as this.Item = new Item() rather than using this.Item = catalogue.Items.CreateObject() so it was being created out of context and when it was added to the order, although the order itself was created from the local context, when the Item was added to it this was somehow dirtying up the context but for some reason this only showed up as a problem when I added the next related object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM