Search code examples
c#entity-frameworkc#-4.0entity-framework-5table-per-type

TPT - How to query appropriate child when an instance of base class is selected?


I'm attempting to determine if my current design using a Table-Per-Type hierarchy is the best way for me to go about the following:

For example, I have 3 child classes (Manager, Executive, Employee) that all inherit from my base Person. I then would like to display all instances of Person inside a grid view for end-users to select and then edit their associated data. However, my question pertains to how to query the appropriate type when a Person is selected. What I'm currently doing is something like the following for the Person class:

public class Person 
{
    Guid PersonID { get; set; }    
    string FirstName { get; set; } 
    string LastName { get; set; }   
    string PersonType { get; set; } 
}

I then set the PersonType field in each of the child classes when they're instantiated.

Set up binding and wire delegate to the SelectionChanged event

BindingSource peopleBinding = new BindingSource();  
peopleBinding.DataSource = db.People.Local.ToBindingList();
this.peopleGridView.DataSource = peopleBinding;    
this.peopleGridView.SelectionChanged += new EventHandler(peopleGridView_SelectionChanged);

The GridView's SelectionChanged Event

if (peopleGridView.SelectedRows.Count != 1) 
{
     return;
}

Person person = peopleBinding.Current as Person;
if (person == null) 
{ 
     return;
}

switch (person.PersonType) 
{
    case "Employee":         
       Employee employee = db.Employees.Find(person.PersonID);
       // Do Work With Employee
       break;
    case "Manager":
       Manager manager = db.Managers.Find(person.PersonID);
       // Do Work With Manager
       break;
    case "Executive":
       Executive executive = db.Executives.Find(person.PersonID);
       // Do Work With Executive
       break;
    default: 
       throw new ArgumentException (string.Format("Invalid type of person encountered ({0})", person.PersonType);
}

Is there a better way to get an instance of the child class rather than using the PersonType field as some sort of discriminator in determining what DbSet I need to query to get the associated entity?


Solution

  • You can use the is keyword:

    if (person is Employee)
      ...
    else if (person is Manager)
      ...
    else if (person is Executive)
      ...