Can I and should I create one or more views and controllesr for TPH inheritance hierarchy in ASP.NET-MVC
I have read many articles about inheritance from Entity Framework (in ASP.NET-MVC context too), everyone writes about the database side of the problem, but no one is causing the problem from the 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 dbContext we save:
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 Am I also saving public DbSet<Employee> Employees { get; set; }
to dbContext?
Now if I click on the controllers directory, right click and then Add Controller as shown below:
The result is a controller with pointers, details, create, delete, and edit for the class Person
.
Everyone Persons
, including those that are Employees
, will be shown in the list Index.cshtml
. In the view Details.cshtml
Employee Salary
will not be displayed. The Edit.cshtml
Employee view Salary
cannot be edited (it is not displayed). Additionally, the POST Edit
action cannot (maybe?) Bind Salary
depending on whether Person
xor has been edited Employee
. This could be predicted, it is obvious, but how to solve it?
Basic question:
Should I create one controller for each type Person
and Employee
or only one togheter for them?
Should I create one New, Create, Delete, Modify view for each type, or just one and somehow check inside these views what type of object I want to present / edit / create in the field of view ? If I am assuming one controller, how do I resolve the bindings in the action method POST Edit
?
Als, if there is one index page with a list of objects Person
, Employee
how to check what type of object is in the list when navigating to the right Details, Create, Delete, Change views?
The solution that comes to my mind is create two controllers PersonController
, EmployeeController
with all views except Index
view and action for EmployeeController
. Then, based on the type of the object in the list in index.cshtml, different views are rendered.
source to share
No one has answered this question yet
Check out similar questions: