Entity Framework: How to avoid Discriminator column from table?
Could also use Table per Type (TPT).
http://weblogs.asp.net/manavi/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-2-table-per-type-tpt
Table per Type (TPT)
Table per Type is about representing inheritance relationships as relational foreign key associations. Every class/subclass that declares persistent properties—including abstract classes—has its own table. The table for subclasses contains columns only for each noninherited property (each property declared by the subclass itself) along with a primary key that is also a foreign key of the base class table.
Implement TPT in EF Code First
We can create a TPT mapping simply by placing Table attribute on the subclasses to specify the mapped table name (Table attribute is a new data annotation and has been added to System.ComponentModel.DataAnnotations namespace in CTP5.
If you prefer fluent API, then you can create a TPT mapping by using ToTable() method:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<BankAccount>().ToTable("BankAccounts");
modelBuilder.Entity<CreditCard>().ToTable("CreditCards");
}
TPH inheritance needs special column which is used to identify the type of entity. By default this column is called Discriminator
and contains names of derived entities. You can use Fluent-API to define different column name and different values. You can also use your MyType column directly because it is actually a discriminator but in such case you cannot have that column in your entity (column can be mapped only once and if you use it as discriminator it is already considered as mapping).
The name of foreign key column can be again controlled with Fluent-API:
protected override void OnModelCreating(DbModelBuilder modelbuilder)
{
modelbuilder.Conventions.Remove<PluralizingTableNameConvention>();
// Example of controlling TPH iheritance:
modelBuilder.Entity<PaymentComponent>()
.Map<GiftPaymentComponent>(m => m.Requires("MyType").HasValue("G"))
.Map<ClubPaymentComponent>(m => m.Requires("MyType").HasValue("C"));
// Example of controlling Foreign key:
modelBuilder.Entity<Payment>()
.HasMany(p => p.PaymentComponents)
.WithRequired()
.Map(m => m.MapKey("PaymentId"));
}
Add attribute [NotMapped] if the property not going to mapped to column.