Reputation: 4054
I'm working on converting a project from nHibernate to Entity Framework and stuck on a mapping issue with mapping an inheritance.
I have the following base class (shortened for brevity):
public abstract class Status
{
public Guid Id { get; set; }
public string Name { get; set; }
}
public class ProjectStatus : Status
{
}
public class TaskStatus : Status
{
}
Can someone point me in the right direction for how to write the mappings for TaskStatus
and ProjectStatus
to inherit from Status
? I would like to use table-per-hierarchy (all saved in one table using a Discriminator)
Upvotes: 2
Views: 769
Reputation: 33071
Table Per Hierarchy is the default. You shouldn't need to provide any additional setup besides what you already have.
This is taken from the TPH example from weblogs.asp.net:
public abstract class BillingDetail
{
public int BillingDetailId { get; set; }
public string Owner { get; set; }
public string Number { get; set; }
}
public class BankAccount : BillingDetail
{
public string BankName { get; set; }
public string Swift { get; set; }
}
public class CreditCard : BillingDetail
{
public int CardType { get; set; }
public string ExpiryMonth { get; set; }
public string ExpiryYear { get; set; }
}
public class InheritanceMappingContext : DbContext
{
public DbSet<BillingDetail> BillingDetails { get; set; }
}
This will create a single table called BillingDetails with a discriminator column.
Discriminator Column
As you can see in the DB schema above, Code First has to add a special column to distinguish between persistent classes: the discriminator. This isn’t a property of the persistent class in our object model; it’s used internally by EF Code First. By default, the column name is "Discriminator", and its type is string. The values defaults to the persistent class names —in this case, “BankAccount” or “CreditCard”. EF Code First automatically sets and retrieves the discriminator values.
Upvotes: 4