簡體   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