子实体的继承和导航属性

时间:2016-12-23 09:49:09

标签: c# asp.net-core entity-framework-core ef-database-first

我在使用继承时遇到导航属性问题(TPH - 目前EF Core中唯一可用的)。

我的层次结构模型:

public class Proposal
{
    [Key]
    public int ProposalId { get; set; }

    [Required, Column(TypeName = "text")]
    public string Substantiation { get; set; }

    [Required]
    public int CreatorId { get; set; }

    [ForeignKey("CreatorId")]
    public Employee Creator { get; set; }

}

public class ProposalLeave : Proposal
{
    [Required]
    public DateTime LeaveStart { get; set; }

    [Required]
    public DateTime LeaveEnd { get; set; }
}

public class ProposalCustom : Proposal
{
    [Required, StringLength(255)]
    public string Name { get; set; }

}

DbContext的一部分:

public class AppDbContext : IdentityDbContext<User, Role, int>
{

    public DbSet<Employee> Employee { get; set; }
    public DbSet<Proposal> Proposal { get; set; }

    public AppDbContext(DbContextOptions<AppDbContext> options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<Proposal>()
            .HasDiscriminator<string>("proposal_type")
            .HasValue<Proposal>("proposal_base")
            .HasValue<ProposalCustom>("proposal_custom")
            .HasValue<ProposalLeave>("proposal_leave");

    }
}

好的,让我们谈谈。正如您在父Proposal模型中看到的,我有属性CreatorId - 对Employee实体的引用。在Employee模型中我想要有两个导航属性来加载创建的子类型的Proposals,如下所示:

public class Employee
{
    public ICollection<ProposalCustom> CreatedProposalCustoms { get; set; } 
    public ICollection<ProposalLeave> CreatedProposalLeaves { get; set; } 

}

但它会导致迁移错误。应用迁移后,我在Proposal表中有两个对Employee实体(CreatorId,EmployeeUserId)的引用,而不是一个(CreatorId)。当我将导航属性更改为:

public class Employee
{      
    public ICollection<Proposal> CreatedProposals { get; set; } 
}

模型是正确的(Proposal表中只有一个Employee引用),但我仍然不能单独包含()到Employee模型CreatedProposalCustoms和CreatedProposalLeaves。

问题可能在我的DbContext配置中,但我不知道如何正确设置它:/

1 个答案:

答案 0 :(得分:4)

问题在于,当您需要导航属性时,EF Core还将创建两个您已经找到的外键。

一种解决方法可能是non-mapped navigation properties,它只是用基类包装集合的转换。

public class Employee
{
    public IDbSet<Proposal> Proposals { get; set; } 
    [NotMapped]
    public IQueryable<ProposalCustom> CreatedProposalCustoms { get; } => Proposals.OfType<ProposalCustom>();
    [NotMapped]
    public IQueryable<ProposalLeave> CreatedProposalLeaves { get; } => Proposals.OfType<ProposalLeave>();
}

两个非映射属性只是Proposals.OfType<T>()

的简写

或者如果你想要它更通用:

public class Employee
{
    public IDbSet<Proposal> Proposals { get; set; } 
    public IQueryable<T> AllProposals<T>() where T :Proposal => Proposals.OfType<T>();
}

然后将其用作employee.AllProposals<ProposalLeave>().Where(p => p.LeaveStart >= DateTime.Now).ToListAsync()