This question is about Controllers, the code that is generated with Model association and inheritance using the Code First Entity Framework Approach.
I have the following Models setup with associations and inheritance.
[Table("User")]
public class User {
[Key]
public int UserId { get; set; }
public string Username { get; set; }
}
[Table("UserProfile")]
public class UserProfile {
[DatabaseGenerated(DatabaseGeneratedOption.None)]
[Key, ForeignKey("User")]
public int UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual User User { get; set; }
}
[Table("Client")]
public class Client : UserProfile {
public bool Approved { get; set; }
}
I then generate a Controller in VS2010, setting the Template to “Controller with read/write actions and view, using Entity Framework”, Model class to “Client” and Data context class to my context class.
This generates the following Index method.
public class ClientController : Controller {
private DataContext db = new DataContext();
public ViewResult Index() {
var users = db.UserProfiles.Include(u => u.User);
return View(users.ToList());
}
...
}
How come it is not like the following?
public class ClientController : Controller {
private DataContext db = new DataContext();
public ViewResult Index() {
var users = db.Clients.Include(u => u.User);
return View(users.ToList());
}
...
}
Or maybe this?
public class ClientController : Controller {
private DataContext db = new DataContext();
public ViewResult Index() {
var users = db.UserProfiles.OfType<Client>().Include(u => u.User);
return View(users.ToList());
}
...
}
Also, the Create method uses
db.UserProfiles.Add(client);
I was wondering why the following is not used?
db.Clients.Add(client);
Any recommendations on which approach I should be using?
The answer lies in how entity framework handles inheritance in models. This scenario is called as “Table per hierarchy” inheritance. When you run the code and have a look at the tables generated, you will see that UserProfile and client data both are getting stored in one table only. As in this model a differentiator column will be used to understand what is the type object , but both the data will be stored in one table only. Hence for table per hierarchy scenario the controller stub is generated with base class model only.
This can give you better insight :
http://weblogs.asp.net/manavi/archive/2010/12/24/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-1-table-per-hierarchy-tph.aspx
Not sure why OfType() is not used, but it seems that VS only generates generalized code.