假设我有以下型号
public class Human
{
public int HumanId {get;set;}
public int Gender {get;set;} // 0 = male, 1 = female
public int? FatherId {get;set;}
[ForeignKey("FatherId")]
public virtual Human Father {get;set;}
public int? MotherId {get;set;}
[ForeignKey("MotherId")]
public virtual Human Mother {get;set;}
public virtual List<Human> Children {get;set;}
}
好的,这是一种自我引用的方法。对于父/母映射,我通过在我的DbContext类中编写此代码找到了一个解决方案
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Human>()
.HasOptional(h => h.Father)
.WithMany()
.Map(h => h.MapKey("Father"));
modelBuilder.Entity<Human>()
.HasOptional(h => h.Mother)
.WithMany()
.Map(h => h.MapKey("Mother"));
}
但我对儿童财产感到不满,因为它取决于一个条件(性别) 通常我会写这样的东西
public virtual List<Human> Children
{
get
{
if (this.Gender == 0)
return Context.Humans.Where(x => x.FatherId == this.Id).ToList();
else if (this.Gender == 1)
return Context.Humans.Where(x => x.MotherId == this.Id).ToList();
else
return null;
}
}
但在我的Model类中,我不了解上下文。
那么解决这个问题的最佳方法是什么?目前我有一个方法
public List<Human> GetChildren(Human human) { ... }
在我的DbContext类中,但我更愿意在我的模型中使用它。有可能吗?
答案 0 :(得分:0)
再创建一个外键作为普通父键。没有对它进行测试,但理论上它应该可行
public class Human
{
public int HumanId {get;set;}
public int Gender {get;set;} // 0 = male, 1 = female
public int ParentId { get; private set; }
public virtual Human Parent { get; private set;}
public int FatherId {get; private set;}
public virtual Human Father {get; private set;}
public int MotherId {get; private set;}
public virtual Human Mother {get; private set;}
public virtual List<Human> Children {get;set;}
public void SetParent(Human parent)
{
Parent = parent;
if (parent.Gender ==0)
Father = parent;
else
Mother = parent;
}
}
的DbContext
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Human>()
.HasOptional(h => h.Father)
.WithMany()
.Map(h => h.MapKey("Father"));
modelBuilder.Entity<Human>()
.HasOptional(h => h.Mother)
.WithMany()
.Map(h => h.MapKey("Mother"));
modelBuilder.Entity<Human>()
.HasOptional(h => h.Parent)
.WithMany(x => x.Children)
.Map(h => h.MapKey("Parent"));
}