I've read plenty of articles about inheritance with Entity Framework(in ASP.NET-MVC context too), everybody writes about database's side of the problem, but nobody brings up view side of the problem.
We got model classes:
public class Person {
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
public class Employee : Person {
public int? Salary { get; set; }
}
and in the dbContext we hold:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser> {
public DbSet<Person> Persons { get; set; }
public ApplicationDbContext() : base("DefaultConnection", throwIfV1Schema: false) {
Configuration.LazyLoadingEnabled = true;
Configuration.ProxyCreationEnabled = true;
}
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
public static ApplicationDbContext Create() {
return new ApplicationDbContext();
}
}
Additional Question: Shoud I keep also public DbSet<Employee> Employees { get; set; }
in dbContext?
Now if I click on Controllers directory right-click then Add Controller like this:
The outcome is getting the controller with Index,Details,Create,Delete,Edit actions for Person
class.
All the Persons
including those which are Employees
will be shown on the Index.cshtml
list. In the Details.cshtml
view Employee's Salary
will not be shown. In Edit.cshtml
view Employee's Salary
can't be edited(it is not visible). Furthermore POST Edit
action cannot(can it?) bind Salary
depending did Person
xor Employee
was edited. This could've been predicted, it is kind of obvious, but how to solve this?
Main question:
Should I create one controller for each type Person
and Employee
or only one for them togheter?
Should I create one Details,Create,Delete,Edit view for each type or only one and somehow check inside those views what type of object I want to present/edit/create in view? If I suppose to have one controller how to solve bindings in POST Edit
action method?
Als if there is going to be one Index page with list consisting both Person
, Employee
objects how to check in the view what type of object is in the list when navigating to right Details,Create,Delete,Edit views?
Examplatory solution which comes to my mind: Create two controllers PersonController
, EmployeeController
with all the views, besides Index
view and action for EmployeeController
. Then basing on type of object in the list in index.cshtml lead to different views.