Thursday, July 28, 2011

Entity Framework 4.1 Primary Key Convention

I’m very pleased with the move to EF 4.1. Using a code first approach to implement my Repository pattern has reduced complexity and given me additional control over my code base and that makes me very happy. I want to point out one area that is a potential sticking point when implementing your entities.

In our system we have a number of entities whose tables have primary keys that are not identities. These entities have their IDs set via initial load scripts at the time the database is deployed using initialization scripts. As a result, the ID fields are simply INTs. The repository for these entities supports adding new entities and require the caller to set the IDs on their entities prior to calling save.

The point of contention comes from the fact that Entity Framework, by default, considers properties marked as [Key] to be identities. You must supply an additional data annotation attribute to override this behavior. The attribute you must apply to your key field is:

[DatabaseGenerated(DatabaseGeneratedOption.None)]

Forgetting to apply this attribute will cause Entity Framework to generate SQL statements on insert that attempt to rely on the key being auto-generated by the identity. The result is a error when you attempt to insert new data that your ID field cannot be NULL.

Using data annotations on your entities allows you to customize numerous behaviors that Entity Framework provides as well other consumers of your entities include data binding for your UI.