实体框架继承配置出错

本文关键字:出错 配置 继承 框架 实体 | 更新日期: 2023-09-27 18:17:29

我有一个抽象类Person

public abstract class Person : Entity
{
    public string PassportFirstName { get; set; }
    public string PassportLastName { get; set; }
    public string InternationalFirstName { get; set; }
    public string InternationalLastName { get; set; }
    public PersonSocialIdentity SocialIdentity { get; set; }
    public PersonContactIdentity ContactIdentity { get; set; }
    public DateTime ? BirthDate { get; set; }
    protected Person()
    {
    }
}

Person衍生出EmployeeStudent等具体类

public class Employee : Person
{
    public Employee() : base()
    {
    }
}

和配置类也通过继承链接:

public abstract class PrincipalEntityConfiguration<T>
    : EntityTypeConfiguration<T> where T : Entity
{
    protected PrincipalEntityConfiguration()
    {
        HasKey(p => p.Id);
        Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
    }
}
public abstract class PersonConfiguration<T> : PrincipalEntityConfiguration<Person> where T : Person
{
    protected PersonConfiguration()
    {
        HasRequired(p=>p.ContactIdentity).WithRequiredPrincipal();
        HasRequired(p=>p.SocialIdentity).WithRequiredPrincipal();
    }
}
public class EmployeeConfiguration : PersonConfiguration<Employee>
{
    public EmployeeConfiguration()
    {
        ToTable("Employees");
    }
}

它们在上下文中被调用:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new EmployeeConfiguration());
        modelBuilder.Configurations.Add(new StudentConfiguration());
        base.OnModelCreating(modelBuilder);
    }

,我得到了一个异常:

类型' em . entities . domain . university '的配置。已经添加了Person。使用Entity()或ComplexType()方法来引用现有的配置。

很明显,这是因为在上下文中有双重的Person Configuration。我该如何解决这个问题?

实体框架继承配置出错

EntityTypeConfiguration<Employee>代替PersonConfiguration<Employee>:

public class EmployeeConfiguration : EntityTypeConfiguration<Employee>
{
    public EmployeeConfiguration()
    {
       ToTable("Employees");
    }
}