Cannot insert explicit value for identity column in table - code-first with EF generated DB RRS feed

  • Question

  • Hi, I've got a very simple code-first generated EF model, with an EF generated DB. Whenever I try to insert, I get:

    Cannot insert explicit value for identity column in table 'XXXX' when IDENTITY_INSERT is set to OFF.

    Given the db is being created by EF, is this a bug?
    Wednesday, March 17, 2010 12:40 PM


  • Hi. I could not reproduce this problem, but I do have some thoughts on the error. When you create a simple model in the designer, it automatically creates an Id field for your entity. That Id field is a primary key and is also an identity column. As such, it will be automatically assigned and incremented without you having to specify any values for it. When you perform your insertion, I'm wondering if you're also assigning a value for the Id field? You should only have to assign values to the non-identity fields of your entity, and then this error shouldn't happen.

    With that said, I couldn't reproduce the problem here by manually assigning a value to the Id field. Instead, the insert ignored the value I passed and simply used the identity to increment the previous Id value in my table.

    Let me know more details if you're still having this problem, and we'll see if we can't figure it out. Thanks!


    Thursday, April 8, 2010 3:17 PM