views:

99

answers:

1

VB .NET 4 WinForms application.

I have a (DevExpress) grid bound to an IEnumerable(Of MyClass). Whenever a new row is added, the ID defaults to zero (0). On trying to SaveChanges, EntityFramework doesn't realise that being an identity field means it should ignore any contents on insert and just insert the other values. I can't specify null / Nothing because it just keeps the ID as zero.

I can add and save instances of MyClass manually, but I'm trying to get it to work where the grid handles adding/initialising/etc new entries. As far as I can tell, the problem is not with the grid but with Entity Framework and the generated SQL and entity classes.

{"Cannot insert explicit value for identity column in table 'MyClasses' when IDENTITY_INSERT is set to OFF."}

Any assistance to prevent me from throwing my laptop out a window would be greatly appreciated!

+3  A: 

If a property of an Entity is an Identity (auto-incrementing value) in the database is specified in the StorageModel of your Entity Model. Perhaps this setting is not correct for your particular field. You can check this by opening the edmx file of your model and looking into the StorageModels section. It should look like this:

<edmx:StorageModels>
  ...
  <EntityType Name="MyClass">
    <Key>
      <PropertyRef Name="ID" />
    </Key>
    <Property Name="ID" Type="..." Nullable="..." StoreGeneratedPattern="Identity" />
    ...
  </EntityType>
  ...
</edmx:StorageModels>

StoreGeneratedPattern must be set to Identity. If there is None or the attribute is missing (which defaults to None) you get indeed the error you described since EntityFramework doesn't know in this case that ID is an identity and will issue a value for the column in the generated SQL-INSERT statement.

(Make sure you are really checking the edmx:StorageModels section in the edmx file. The edmx:ConceptualModels section has an attribute annotation:StoreGeneratedPattern in the property as well but its setting doesn't matter for your specific problem. (I think that's only important when a database gets created from a model, but I'm not sure.))

Slauma
Oddly enough, other entities have SGP specified in the EDMX, and in the designer they all have the same settings (entity key, identity etc) but only the class in question lacks StoreGeneratedPattern="Identity" in the EntityType section. The amount of XML editing invokved so far has been very frustrating... but many many thanks for answering what MSDN and several high-profile ORM and .NET bloggers could not!
FerretallicA
I was wondering how this setting could be missing if the column in the database is an identity. Did you perhaps change the column later (after you created your model for the first time) from a non-identity to an identity column in the DB table and forgot to update your model from the database? But honestly I am even not sure if it really gets updated automatically. It's something to be tested.
Slauma