EntityFramework CodeFirst and AutoKey Generation

Posted by Peter Kellner on January 15, 2012 · 3 mins read

 

This one had me a little stumped, and as usual, there are not enough examples in the Microsoft documentation to be very helpful. I’m using EntityFramework CodeFirst with Visual Studio 2011.  Let’s assume you create a class as follows:

 

public class CongressNumber
    {
        [Key]
        public int CongressNumberValue { get; set; }
    }

Then, you manually set the value of CongressNumberValue to 112.  I’d certainly think that is a reasonable thing to do. I know that the Microsoft guys often special case Id or id, but hard to believe they would take something like CongressNumberValue and assume I meant that to be an autogenerating Identity column.  Well, it seems they do that and the doc’s don’t even mention it. 

After first, finding the page on annotations, I discovered that what we really need to set is this to have it work as we want (with no identity key generation).

 public class CongressNumber
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int CongressNumberValue { get; set; }
    }

I found this after drilling down some in there doc.  What surprises me is that no where does it mention that if you have a string, that does not get database generated, but if you have an int, that does.  I wonder what happens if you have a Guid? (I’ll leave that up to someone who wants to use a guid).

I would have loved to put in my own comments on the page: http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.databasegeneratedoption(v=vs.103).aspx but there was no user comment section.  Oh well.

To be fair, on the page: http://msdn.microsoft.com/en-us/library/gg197525(v=vs.103).aspx it does explain about identity and integers but when I had my issue, I was already on the detail page.  Seems to me the detail page should have more information on it than the summary page that leads in.  The only reason I found it was because while writing this post, I went back to get the proper links.

 

image

HTH’s.