0

I am using Entity Framework 5 code-first and I have overridden the SaveChanges method. In SaveChanges, I want to identify any entities with an EntityState == EntityState.Added (I can do this easily enough) however I then want to identify any columns in those entities which have been defined as a primary key, have their HasDatabaseGeneratedOption property set to DatabaseGeneratedOption.None and currently have Null value.

I need to identify these columns as my database currently has some columns defined as primary keys which need to be manually populated via code. I figured I could tackle this population of columns in SaveChanges on an insert but am stumped as to how to identify them.

How do I query column definitions in SaveChanges? I obviously know how to examine the data value

1 Answer 1

1

You need to look at the data model, get the property that holds the primary key and see if it has the attribute you want. See an example here: http://weblogs.asp.net/ricardoperes/entity-framework-metadata. However, this will not work if you are not using attributes, but instead customizing the model in OnModelCreating.

Sign up to request clarification or add additional context in comments.

4 Comments

Great blog post! Is the EntityFramework metadata model documented somewhere? Your examples are a great illustration of how to get at the information I just don't necessarily know where to look for the HasDatabaseGeneratedOption property. If I use your example extension method of GetIdProperties, I get the ID. I am not customizing the model in OnModelCreating, but I am using a Map class to define what the entity looks like. The entity map class sets the HasDatabaseGeneratedOption
Also, am I understanding you correctly that it is not possible to add a custom property (unless it is an Attribute on the entity itself) and read it out later? Can it be an attribute on the Map Class and not the entity itself?
There isn't much documentation about that, I'm afraid. My solution works with mapping attributes; you can get the attribute from the id property using PropertyInfo.GetCustomAttributes(). The attribute you want is DatabaseGeneratedAttribute.
Do you have any thoughts on my other question: stackoverflow.com/questions/25897957/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.