我有一个班级,就像这样
public MyObject {
public long Id { get; set; }
public string Name {get; set; }
}
我想在这个类和另一个相同类型的对象之间建立一个链接。所以我需要另一个对象来处理多对多关系,这很好,就像这样
public MyRelationship {
public long Id { get; set; }
public string Name { get; set; }
}
但我如何配置其余部分。我在网上尝试了一些例子,但它们的对象太不相同了。
我已尝试将链接的导航属性添加到MyRelationship,如此
public MyRelationship {
public long Id { get; set; }
public string Name { get; set; }
public MyObject Parent { get; set; }
public MyObject Child { get; set; }
}
还有2个MyObject集合,如此
public MyObject {
public long Id { get; set; }
public string Name {get; set; }
public virtual ICollection<MyRelationship> ParentRelationships { get; set; }
public virtual ICollection<MyRelationship> ChildRelationships { get; set; }
}
然后在我的配置文件中添加了
// relationships
this.HasMany(e => e.ParentRelationships)
.WithRequired(e => e.Parent)
.HasForeignKey(e => e.ParentId)
.WillCascadeOnDelete(false);
this.HasMany(e => e.ChildRelationships)
.WithRequired(e => e.Child)
.HasForeignKey(e => e.ChildId)
.WillCascadeOnDelete(false);
但我得到错误,比如
导航属性&#39; ChildRelationships&#39;在类型&#39; MyObject&#39;上声明已配置有冲突的外键。答案 0 :(得分:0)
你为什么不这样做?
public MyObject{
public long Id { get; set; }
public string Name { get; set; }
public ICollection<MyObject> Parents { get; set; }
public ICollection<MyObject> Children { get; set; }
}