Entity Framework - error "the relationship between two objects cannot be determined", but I think I use the same context

In my ViewModel, I have code like this:

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 center is new and the new order, I got into the old "The relationship between two objects cannot be determined because they are tied to different ObjectContext objects", which seems to me a little unfair - I just can not understand what I need done to make them more similar to the same object context. I assume this is due to some fundamental misunderstanding of the behavior of the Entity Framework.

+3
source share
2 answers

. @Slauma //do stuff..., , .

, , this.Item = new Item() this.Item = catalogue.Items.CreateObject(), , , , - , - , .

+2

. , order deliveryCentre , . using Save -:

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

catalogue.

+3

All Articles