【发布时间】:2016-05-27 18:27:45
【问题描述】:
我收到了错误
Multiplicity constraint violated. The role 'BegrotingsCategorie_children_Source' of the relationship 'NET.DAL.EF.BegrotingsCategorie_children' has multiplicity 1 or 0..1.
尝试从我的数据库中读取“BegrotingsCategorie”时。 这段代码触发了异常
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 映射?请记住,它必须对 Category 类具有 FK 才能建立一对多关系。
-
begrotingsCategorie 类如上所示,'children' 列表有来自同一类的 Parent。如果我在孩子上方添加 [ForeignKey("Parent")],我会收到此错误
The ForeignKeyAttribute on property 'children' on type 'NET.BL.Domain.Begroting.BegrotingsCategorie' is not valid. The foreign key name 'Parent' was not found on the dependent type 'NET.BL.Domain.Begroting.BegrotingsCategorie'. The Name value should be a comma separated list of foreign key property names. -
您需要一个 int 类型的 Id,您可以在其中添加属性 ForeignKey。这允许您的 DBMS 使用 ForeignKey=primary key 约束自行加入您的表。
-
嗯,但奇怪的是它直到几个小时前才起作用。而且我的数据库中有 3500 行数据,所以添加新的 ForeignKey 属性并不容易。。
-
你到底做了什么改变?如果没有定义外键,这种关系可能永远不会起作用。
标签: c# mysql asp.net-mvc entity-framework