繁体   English   中英

实体框架 - “两个对象之间的关系无法定义”错误,但我认为我使用的是相同的上下文

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

在我的ViewModel中,我有一些代码:

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();

    }

因此,当交付中心是新的并且订单是新的时,我被旧的“两个对象之间的关系无法定义,因为它们附加到不同的ObjectContext对象”错误,这对我来说似乎有点不公平 - 我只是无法弄清楚我需要做些什么来使它们更多地属于同一个对象上下文。 我认为这是由于对实体框架行为的一些基本误解。

你没有处理你的背景。 有可能实体orderdeliveryCentre一个附加到仍然保存对实体的引用的旧上下文。 您可以using Save方法中的using语句创建和处置上下文,而不是将其用作成员变量:

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

并删除私人catalogue成员。

解决方案结果只是间接与错误信息相关 - @Slauma询问了//do stuff...占位符以及当我评论这些错误消失时。

事实证明那里有另一个关系,我在那里创建对象this.Item = new Item()而不是使用this.Item = catalogue.Items.CreateObject()所以它是在上下文之外创建的尽管订单本身是从本地上下文创建的,但订单本身是从本地上下文创建的,当项目被添加到它时,这在某种程度上弄脏了上下文,但由于某种原因,这只是在我添加下一个相关对象时出现的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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