1

假设我有以下模型

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"));

    }

但是我正在努力处理 Children 属性,因为它取决于条件(性别)通常我会写这样的东西

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;
    }
}

但在我的模型课中,我不知道上下文。

那么解决这个问题的最佳方法是什么?目前我有一个方法

public List<Human> GetChildren(Human human) { ... }

在我的 DbContext 类中,但我更愿意在我的模型中使用它。有可能吗?

4

1 回答 1

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;
    }
}

数据库上下文

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"));

}
于 2013-05-28T12:02:48.953 回答