Tim
Tim

Reputation: 3038

EF discriminators with chained inheritance

I'm trying to replace the discriminator column with my own constant (rather than EF's string constants). My classes are as follows:

[Table("stor_store")]
public abstract StoreBase { /* Base fields */ }

public StoreTemplate : StoreBase {/* Extra fields */ }

public Store : StoreBase {/* Extra fields */ }

[Table("cust_customer")]
public Customer : Store { /* Extra fields */ }

[Table("engi_engineer")]
public Engineer : Store {/* Extra fields */ }

I've been trying to map the column using fluent API:

modelBuilder.Entity<StoreBase>()
    .Map<StoreTemplate>(m => m.Requires("stor_type").HasValue((byte)0)
    .Map<Store>(m => m.Requires("stor_type").HasValue((byte)1))
    .Map<Customer>(m => m.Requires("stor_type").HasValue((byte)2))
    .Map<Engineer>(m => m.Requires("stor_type").HasValue((byte)3));

However EF always creates the discriminator column. This mapping has worked before, but the double-nested inheritance seems to have thrown it. Thanks for any help.

Upvotes: 1

Views: 291

Answers (1)

JDandChips
JDandChips

Reputation: 10110

I can see your problem here, and I guess it's down to the fact that Store has already been assigned a value, so perhaps when you try to set the value for the inherited Entities it fails?

You could try a different order: Reordering doesn't help!

modelBuilder.Entity<StoreBase>()
.Map<StoreTemplate>(m => m.Requires("stor_type").HasValue((byte)0)
.Map<Customer>(m => m.Requires("stor_type").HasValue((byte)2))
.Map<Engineer>(m => m.Requires("stor_type").HasValue((byte)3))
.Map<Store>(m => m.Requires("stor_type").HasValue((byte)1));

An alternative approach

However, as your inheritance has become more complex maybe you should consider implementing something like the "Table Per Type" (TPT) strategy? This approach would separate your types into their own tables, save on empty columns for smaller discriminators and give you a clearer structure.

enter image description here

You can find a full description is details here: http://weblogs.asp.net/manavi/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-2-table-per-type-tpt

Upvotes: 1

Related Questions