我有一个名为ParentId的Property实体,该实体链接到名为Parent的导航属性。这种关系似乎工作正常但我的问题是现在我想要另一个导航属性,它将是一个“Child”项目列表,其中父项与实体ID相同。
我在我的FK属性中尝试了“ID”,“父”,但我得到“类型为'jrSite.Core.SiteModel'的属性'Children'上的ForeignKeyAttribute无效”错误。
我如何告诉EF我希望该导航属性在SiteModel表中搜索具有匹配父ID的项目?
我的课程在下面
public class SiteModel
{
public SiteModel() { }
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
public DateTime Created { get; set; }
[ForeignKey("Creator")]
public int CreatorID;
public SiteAccount Creator { get; set; }
[ForeignKey("Owner")]
public int OwnerID;
public SiteAccount Owner { get; set; }
[ForeignKey("Parent")]
public int? ParentID;
public SiteModel Parent { get; set; }
[ForeignKey("Parent")]
public List<SiteModel> Children { get; set; }
public SiteModel(SiteAccount creator, SiteAccount owner)
{
Creator = creator;
Owner = owner;
Created = DateTime.Now;
}
}
答案 0 :(得分:0)
覆盖DBContext类中的OnModelCreating并添加以下代码:
modelBuilder.Entity<SiteModel>()
.HasRequired<SiteAccount>(s => s.Creator);
modelBuilder.Entity<SiteModel>()
.HasRequired<SiteAccount>(s => s.Owner);
答案 1 :(得分:0)
ParentID/Parent
nav属性已经处理好这种关系 - 摆脱ForeignKey
属性声明中的Children
属性。我刚刚测试了以下内容并且有效:
public class HierarchicalEntity
{
public int Id { get; set; }
public string Description { get; set; }
public int? ParentId { get; set; }
public virtual HierarchicalEntity Parent { get; set; }
public virtual ICollection<HierarchicalEntity> Children { get; set; }
}
using (var db = new TestEntities())
{
var parent = new HierarchicalEntity();
db.HierarchicalEntity.Add(parent);
var children = new List<HierarchicalEntity>()
{
new HierarchicalEntity() { Parent = parent },
new HierarchicalEntity() { Parent = parent }
};
children.ForEach(c => db.HierarchicalEntity.Add(c));
db.SaveChanges();
}