0
votes

I have a class Employee that looks like the following:

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Manager { get; set; }
}

I have another class Manager that extends this class and adds no other functionality:

public class Manager : Employee
{
}

In my DbContext derived class I have:

public DbSet<Employee> Employees { get; set; }
public DbSet<Manager> Managers { get; set; }

I want employee's with Employee.Manager == 1 to be added to the Managers DbSet and the employee's with Employee.Manager == 0 to be added to the Employees DbSet.

The database table is structured in this way and I need to be able to do something like this, because I have another class which has a foreign key to an employee and one to a manager.

How can I accomplish this or is there another way to solve my problem?

1
In other words, you are using Table Per Hierarchy, and the Manager value is your Discriminator? - Claies

1 Answers

1
votes

In order For Code First to use your custom discriminator column, you must modify the default behavior using the Fluent API.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Employee>()
        .Map(e => e.Requires("Manager").HasValue(0))
        .Map<Manager>(m => m.Requires("Manager").HasValue(1));

    base.OnModelCreating(modelBuilder);
}

A couple things to note:

  • There is only one DbSet<Employee> in this scenario. A DbSet<Manager> will not work. An Employee retrieved from the database can be identified as a manager by checking the Manager value, and a var manager = new Manager() will automatically be assigned the correct discriminator.

  • ALL types which inherit from Employee must be given a value for the Discriminator in this modelBuilder. If you skip an inherited class, you will receive runtime errors when accessing any class in the hierarchy.