簡體   English   中英

實體框架v4 - 無法定義兩個對象之間的關系,因為它們附加到不同的ObjectContext對象

[英]Entity Framework v4 - The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects

這是關於SO的第一個問題,盡管我長期以來一直將它作為資源使用。

首先,我知道有很多關於這個主題的問題,我想我已經嘗試了所有各種解決方案但沒有用,但也許我錯過了一些基本的東西。

我在asp.net MVC網絡應用程序上使用EF4,不確定還有什么你需要知道但是如果是這樣的話就大喊大叫。

據我所知,我只使用一個上下文“db”而我沒有使用“using”語句,所以我看不到上下文被處理掉了,至少不是故意的,但我還是一直在打上面的錯誤。

情況是我有一個動作結果,它創建了一組條目“ReportSections”連接到主模型“Report”,基於通過ClaimGroup連接到Report的“Claims”(見下文)。

因此,我的(簡化)課程看起來像這樣;

public partial class Claim
{
    public Claim()
    {
        this.ReportSections = new HashSet<ReportSection>();
        this.Reports = new HashSet<Reports>();
    }

    public int id {get; set;}
    //other stuff

    public virtual ICollection<Reports> Reports {get; set;}
    public virtual ICollection<ReportSections> ReportSections {get; set;}
}

public partial class ClaimGroup
{
    public ClaimGroup()
    {
        this.Claims = new HashSet<Claims>();
    }

    public int id {get; set;}
    //other stuff

    public virtual ICollection<Claims> Claims {get; set;}
    public virtual ICollection<ReportSections> ReportSections {get; set;}
}

public partial class Report
{
    public Report()
    {
        this.ReportSections = new HashSet<ReportSection>();
    }

    public int id {get; set;}
    public int ClaimGroupId {get; set;}
    //other stuff

    public virtual ICollection<ReportSections> ReportSections {get; set;}
    public virtual ClaimGroup ClaimGroup {get; set;}
}

public partial class ReportSection
{
    public int id {get; set;}
    public int ClaimId {get; set;}
    public int ReportId {get; set;}
    public int Position {get; set;}
    //other stuff

    public virtual Report Report {get; set;}
    public virtual Claim Claim {get; set;}
}

[為避免疑問,我很高興聲明和ClaimGroups之間的多對多關系正常工作,因為它在網站的其他區域運行。

我的控制器有以下內容;

public ActionResult BuildSections(int id)
{
    Report r = db.Reports.Find(id);
    int i = 0;
    foreach(Claim c in r.ClaimGroup.Claims)
    {
        r.ReportSections.Add(new ReportSection { Claim = c, Position = i});
        i++;
    }
    db.SaveChanges();
}

它真的很煩人,因為它似乎並不復雜,但我顯然做錯了什么。

提前致謝。

SY

編輯

保存回數據庫時會觸發錯誤,因此在此示例中它處於打開狀態

db.SaveChanges();  

但是,在我嘗試尋找解決方案的各種嘗試中,我也嘗試過

db.ReportSections.Add(new ReportSection {...}); 

那條線上發生了錯誤。

感謝那些花時間給我一些指示的人。 我找到了這個問題,並認為我會發布它,以防它幫助那些造成這樣一個學校男孩錯誤的人。

我的Claim類由兩個部分類組成,其中一個有一些計算字段,其中一個使用另一個上下文。 錯誤所指的是上面的ActionResult中沒有任何內容,但當然在保存更改時無法解決這兩個問題。

再次感謝

SY

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM