简体   繁体   English

实体框架继承配置出错

[英]Entity Framework inheritance configuration goes wrong

I have an abstract class Person . 我有一个抽象类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()
    {

    }
}

And from Person there are derived concrete classes like Employee and Student Person派生出具体的类,例如EmployeeStudent

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

And configuration classes chained by inheritance too: 并且配置类也通过继承链接在一起:

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

And they are called in context : 它们在上下文中被调用:

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

and I got an exception: 我有一个例外:

A configuration for type 'EMIS.Entities.Domain.University.Person' has already been added. 已添加“ EMIS.Entities.Domain.University.Person”类型的配置。 To reference the existing configuration use the Entity() or ComplexType() methods. 要引用现有配置,请使用Entity()或ComplexType()方法。

Clearly, it happens because in context there are doubly called Person Configuration. 显然,发生这种情况是因为在上下文中双重称为“人员配置”。 How can I fix this problem? 我该如何解决这个问题?

Use EntityTypeConfiguration<Employee> instead PersonConfiguration<Employee> : 使用EntityTypeConfiguration<Employee>代替PersonConfiguration<Employee>

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM