Iskander Raimbaev
Iskander Raimbaev

Reputation: 1362

Entity Framework inheritance configuration goes wrong

I have an abstract class 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

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. To reference the existing configuration use the Entity() or ComplexType() methods.

Clearly, it happens because in context there are doubly called Person Configuration. How can I fix this problem?

Upvotes: 0

Views: 437

Answers (1)

Masoud
Masoud

Reputation: 8171

Use EntityTypeConfiguration<Employee> instead PersonConfiguration<Employee>:

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

Upvotes: 1

Related Questions