2016-05-27 71 views
0

試圖從我的數據庫中讀取一個「BegrotingsCategorie」當我收到錯誤違反了EF多重性約束。角色...的關係......有多重1或0..1

Multiplicity constraint violated. The role 'BegrotingsCategorie_children_Source' of the relationship 'NET.DAL.EF.BegrotingsCategorie_children' has multiplicity 1 or 0..1. 

。 這段代碼觸發異常

public BegrotingsCategorie ReadBegrotingsCategorie(int begrotingsCategorieId) 
     { 
      return _ctx.Begrotingscategorieen.Find(begrotingsCategorieId); 
     } 

我BegrotingsCategorie模型看起來像這樣

[Table("tblBegrotingsCategorieen")] 
    public class BegrotingsCategorie 
    { 
     [Key] 
     public int BegrotingsCategorieId { get; set; } 
     public string Informatie { get; set; } 
     public double Uitgaven { get; set; } 
     public Begroting Begroting { get; set; } 
     public BegrotingsCategorie Parent { get; set; } 
     public double Percentage { get; set; } 
     public double BerekendLoon { get; set; } 

     public virtual ICollection<BegrotingsCategorie> children { get; set; } 
     public virtual ICollection<Actie> Acties { get; set; } 

    } 

我不知道如何解決這個..

編輯在 某些行數據庫

database

第一行是父所以其Parent_BegrotingsCategorieId爲NULL, 它有1個小孩與Parent_BegrotingsCategorieId 1對自己誰也有多個孩子,讓他們有Parent_BegrotingsCategorieId 2

添加我的數據是這樣

public BegrotingsCategorie AddBegrotingsCategorie(string informatie, Begroting begroting, BegrotingsCategorie parentCategorie) 
     { 
      BegrotingsCategorie begrotingsCategorie = new BegrotingsCategorie() 
      { 
       Informatie = informatie, 
       Begroting = begroting, 
       Parent = parentCategorie 
      }; 
      return _repo.CreateBegrotingsCategorie(begrotingsCategorie); 
     } 
+0

您可以顯示BegrotingsCategorie類和這些類的Fluent API映射嗎?請記住,它必須具有FK才能建立1對多關係。 – DevilSuichiro

+0

begrotingsCategorie類如上所示,列表'children'具有來自同一個類的Parent。 如果我在上面的孩子上面添加[ForeignKey(「Parent」)],我得到這個錯誤 '類型'NET.BL.Domain.Begroting.BegrotingsCategorie'屬性'children'的ForeignKeyAttribute無效。在依賴類型「NET.BL.Domain.Begroting.BegrotingsCategorie」上未找到外鍵名'Parent'。 Name值應該是以逗號分隔的外鍵屬性名稱列表.' – willemH

+0

您需要一個int類型的Id,您可以在其中添加屬性ForeignKey。這允許您的DBMS使用ForeignKey =主鍵約束自我加入您的表。 – DevilSuichiro

回答

-1

我覺得你的ICollection<BegrotingsCategorie> children屬性給你的BegrotingsCategorie類噪音。在您的代碼中某處定義了BegrotingsCategorie的一個或零對一的遞歸關係。但是,您正嘗試在您的課程中使用BegrotingsCategorie的一對多關係,方法是將您的財產children聲明爲ICollection。如果你真的不需要它,你可能想要在BegrotingsCategorie課中擺脫children屬性。這可能是一種可能的解決方法。

+0

這不是問題的核心。因爲沒有定義FK,所以EF使用PK = FK,因此找到一對一的關係,但是使用ICollection定義了一對多,這就是導致此錯誤發生的原因。 – DevilSuichiro

+0

@downvoter,你能告訴我們爲什麼你這樣做,所以我們都可以學習新的東西? –

+0

@DevilSuichiro我不知道OP的意圖是什麼,因爲他真的需要'children'屬性,因爲他已經有一個或之前定義的一對一的約束。我邀請你發表你的評論作爲答案,並讓OP決定哪個答案更適合他的需求。 –

相關問題