Entity Framework SaveChanges - how to ignore ID / Identity fields on INSERT
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 thr开发者_StackOverflow中文版owing my laptop out a window would be greatly appreciated!
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.))
精彩评论