Question

I'm working on an EF5 Code First application, and things have been going well so far, but I've hit a bump, and I'm hoping someone can suggest a solution.

Basically, I've got a base class, and a few derived classes, and I'm wondering how to handle their mapping. Here's a ridiculously simplified example:

[Table("Person")]
public class Person
{
  public int PersonId { get; set; }
  public string Name { get; set; }
}

[Table("EmployeePerson")]
public class EmployeePerson : Person
{
  public int HoursWorked { get; set; }
}

[Table("CustomerPerson")]
public class CustomerPerson : Person
{
  public int DollarsSpent { get; set; }
}

So far, this is a typical Table-per-Type scenario, except for the hitch that the base class is not abstract -- it's possible to have a Person who is not an EmployeePerson or a CustomerPerson. I'm having some trouble getting the EF to accept that, and when I try to load such an entity by ID, the ugly query generated by the EF returns no rows.

Has anyone implemented anything like this before? Does TPT-style mapping always require the base class to be abstract? I haven't been able to find any examples to the contrary, but no real confirmation either. I can think of a few ugly workarounds I might be able to use if I have to, but I'd prefer a more elegant solution if there is one.

(One further hitch: I'm working against a third-party database, and so I can't make any changes to the schema.)

Thanks!

Was it helpful?

Solution

If your "ugly" solution is to introduce an abstract base class PersonBase (or similar) and make Person an empty derived class, my comment would be: do it! It isnot ugly at all, because it leaves room to changing Person later without affecting the other derived classes. Currently, that would be much harder. You'd have to introduce the abstract class later, which is a more drastic change in existing code.

About your issue: I can't repro that with EF 5 (VS 2012 .Net 4.5). Maybe there are more things going on in your real model.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top