試圖從我的數據庫中讀取一個「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; }
}
我不知道如何解決這個..
編輯在 某些行數據庫
第一行是父所以其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);
}
您可以顯示BegrotingsCategorie類和這些類的Fluent API映射嗎?請記住,它必須具有FK才能建立1對多關係。 – DevilSuichiro
begrotingsCategorie類如上所示,列表'children'具有來自同一個類的Parent。 如果我在上面的孩子上面添加[ForeignKey(「Parent」)],我得到這個錯誤 '類型'NET.BL.Domain.Begroting.BegrotingsCategorie'屬性'children'的ForeignKeyAttribute無效。在依賴類型「NET.BL.Domain.Begroting.BegrotingsCategorie」上未找到外鍵名'Parent'。 Name值應該是以逗號分隔的外鍵屬性名稱列表.' – willemH
您需要一個int類型的Id,您可以在其中添加屬性ForeignKey。這允許您的DBMS使用ForeignKey =主鍵約束自我加入您的表。 – DevilSuichiro