Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 5 Scaffolding with inheritance uses the wrong entity set

With MVC 5 and EF 6.1 I am using a simple inheritance hierarchy, where class Student inherits from class Person. For both classes I have an entity set (DbSet property) in my database context:

public class DatabaseContext : DbContext
{
    public DbSet<Person> Persons { get; set; }
    public DbSet<Student> Students { get; set; }
}

Now when I ask the scaffolder to generate a controller for Student, the subclass, it uses the Persons entity set, leading to statements such as

    Student student = db.Persons.Find(id);

where the compiler obviously complains that it cannot just convert any Person to a Student.

Is there a way to make sure that the scaffolder uses the correct entity set (Students in this case)?

Note that removing the Persons entity set is not a good solution, because there are other controllers that need that.

like image 601
Pierre America Avatar asked Sep 30 '22 04:09

Pierre America


1 Answers

Use find and replace to change all occurrences in the Controller class of the parent DBSet to the child DBSet eg change Persons to Students.

As you probably know (as I think you raised it) Microsoft have confirmed this is a known bug http://connect.microsoft.com/VisualStudio/feedbackdetail/view/945937/mvc-5-scaffolding-with-inheritance-uses-the-wrong-entity-set but they won't be fixing it.

like image 153
Caltor Avatar answered Nov 03 '22 00:11

Caltor