For some of the properties in my DB I need to manually calculate their Id #, so for those properties I do .Property(p => p.Id).HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.None);
inside OnModelCreating
Then, in the repository I have a method to calculate out the Id for a given type. I would prefer to have the system be intelligent and check to see if the DatabaseGeneratedOption.None
or DatabaseGeneratedOption.Identity
and either return the next Id or 0.
How can I check (from inside a repository) what the DatabaseGeneratedOption
for a given type (T) is?
As I said in a comment, your solution works by virtue of a code-first store model returning the CLR type names from
EntityType
. A database-first store model, however, returns the store names. These names do not necessarily match the CLR type names.To make this method independent of EF's store model, we need to access the store-CLR mapping space (
CSSpace
) and find theEntitySet
(by CLR name) and match itsKeyMembers
with the columns in the store model (Property.Column
), because these columns contain the right value ofIsStoreGeneratedIdentity
. (CLR properties also have this property, but it's always false).So this is what we get (as a method encapsulated in a
DbContext
subtype):Thanks to George's comment I was able to come up with this solution: