Search code examples
c#entity-frameworkentity-framework-ctp5

Entity Framework code first TPH where discriminator is greater than 0


I am defining a model in EF4 CTP5 where I need to map an inherited entity only when the value of an id is greater than 0. the code looks like this.

public class Parent
{
   public int ID { get; set; }
   public string FirstName { get; set; }
   public string LastName { get; set; }
}

public class Child : Parent
{
   public int SchoolID { get; set; }
}

In the OnModelCreating method...

modelBuilder.Entity<Parent>().Map<Child>(
            reg => 
                {
                reg.MapInheritedProperties();
                reg.Requires("SchoolID").HasValue((int)<value greater than 0); <== Pseudo code
            }).ToTable("Users");

Is this sort of thing possible? If not, is it possible to ignore the discriminator altogether?


Solution

  • Not sure about the 'is it possible' part, but it smells a little. I mean, it implies meaning in your data where there really should not be meaning; you'll wind up with long term maintainability problems. The discriminator is there not just to help the ORM figure out which record is of which type, it's also supposed to be (imo) a logical description of the type you're dealing with, for when humans run SQL queries against the db. It also can be used to help with index partitioning. I realize that TPH is a bit of denormalization anyway, but you still want to be able to design a well-indexed db with those in there.

    I'd suggest just letting EF do the discriminator for you based on the type name, which iirc is the default.