Translate

jueves, 3 de abril de 2014

Entity Framework, Code First and Inheritance

We have the following classes structure:

These are the classes code:





We are going to use the TPH (Table Per Hierarchy) way, which means we are going to have only one table for an Hierarchy. In this case we are going to have one table for both Customers and Employees.

In the Data Base Context I need to add all the classes that represent an entity, but when I´m using inheritance  and TPH, I do not need to add the classes which inherits from a main class. I´m going to add only the base class. So the Data Base Context would be as follows:


So, when EF creates the data base from the model this is the table that I´m going to have including Customer and Employees. Note that EF adds a field called Discrimator, which is a string field used by EF to discriminate to which entity does the data belong. In our case this field could contains values like "Customer" or "Employe".


But, what happen when I need to query data from this table?, well I could made queries for the parent object, person, or queries to child objects, customer or employee.

This is an example of ASP.NET Web Forms GridView component using EF and LINQ to access data for Employees:

The GridView in a browser showing data for employees


The aspx code for the GridView

The code for the GridView´s SelecMethod 
Note that we can query for a child object, but in this case we need to use OfType to indicate EF to retrieve only the data from the People table belonging to the Employee Entity.

No hay comentarios: