Using Entity Framework 4 CTP5 Code First and this example
Is it possible to access the discriminator value?
I would like to use it in a projection like
context.BillingDetails.Select(x => new { Number = x.Number, DiscrimitatorValue = /* how do I get the discriminator value? */ });
From this post I understand the discriminator cannot be mapped to a property but is there any other way of accessing it?
I may be late to the game on this one, but I just added a getter property to the base class that returned the name of the current type:
Since by default EF is going to use this same value for the Discriminator field, they will match up.
In EF Core 2.1 (I haven't checked previous versions) it's enough to add
Discriminator
to the base abstract class as private set property. It will be mapped with adequate value.EF by itself will automatically insert appropriate discriminator value to the database and will automatically set it to an object on read.
Why don't you use the following query instead?
To expand on @Michael Black's answer for Entity Framework Core 2.1 (earlier? tested in 2.1.4)
You can use any property name, database field name and data type you want.
Create a property:
Then in your context class with the fluent API via modelBuilder:
This is really useful if you need to build composable queries that e.g., group on the discriminator, etc.
Reason aside, I recently ran into the same problem but believe this is still relevant for v4 of the EF Framework.
First, create a view which selects the discriminator value into two columns.
Secondly, map the view to your entity during context creation:
Thirdly, define your discriminator mapping for your derived class using one of the columns in your view:
Finally, define a getter and a private setter for the other discriminator column in your view with the
DatabaseGenerated
annotation set asComputed
to prevent EF from updating/inserting for this field:You can change the private setter to be protected and set this value explicitly during the construction of your derived entities so that the discriminator has a value prior to being persisted:
After further information from Morteza Manavi in the comments of his post the simple answer is no
To access the discriminator I would have to execute a
SqlQuery
against the database or change my mapping strategy.