Question

Lets say I have some classes:

public class BaseModel
{
    [Key]
    public int Id { get; set; }
}

public class Person : BaseModel
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public DateTime DateOfBirth { get; set; }

    public string Email { get; set; }
}

public class Employee : Person
{
    public string Position { get; set; }

    public decimal Wage { get; set; }

    public PaymentType PaymentType { get; set; }

    public virtual Company Company { get; set; }
}

Currently I have this:

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

    modelBuilder.Entity<Employee>().HasRequired(e => e.PaymentType);
    modelBuilder.Entity<Employee>().Map(t =>
        {
            t.MapInheritedProperties();
            t.ToTable("Employees");
        });

    modelBuilder.Entity<Company>().HasMany(c => c.Employees).WithRequired(e => e.Company).Map(t => t.MapKey("Company_Id"));

}

I get two tables for Person and Employee, but I don't like what MapInheritedProperties() does by adding the Person properties to the Employee table.

How do I make the base class(Person) a foreign key?

Was it helpful?

Solution

In order to use the base class as a foreing key / navigational property without primary key problems. You need to be using Table per Type or Table per Hierarchy.

In your case using that modelBuilder should do it.

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

    modelBuilder.Entity<Employee>().HasRequired(e => e.PaymentType);
    modelBuilder.Entity<Person >().ToTable("Persons");
    modelBuilder.Entity<Employee>().ToTable("Employees");

    modelBuilder.Entity<Company>().HasMany(c => c.Employees).WithRequired(e => e.Company).Map(t => t.MapKey("Company_Id"));
}

With this two table will be created. On names Persons will all fields for a person and one "Employees" for all fields for an employee. Both table will share the same primary key

You can get a really detailed explaination on Mortenza Manavi's blog

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top