Turn on IDENTITY_INSERT in Entity Framework, SQL S

2019-08-04 11:35发布

问题:

Possible Duplicate:
How to Turn on IDENTITY_INSERT in SQL Server 2008?

Trying to insert data via entity framework into a SQL Server 2008 database. I get error

IDENTITY_INSERT is set to OFF

from the application.

I have ran query SET IDENTITY_INSERT Database. dbo. Baskets ON

And got the message back Command(s) completed successfully. But error still occur...?

storeDB.Baskets.Add(cartItem);          
storeDB.SaveChanges();

Occurs at storeDB.SaveChanges();

回答1:

When using an identity column, you need to make sure you have set this appropriately in your EDMX (Entity Framework) model. Your column should look like this:

Is your column set to be StoreGeneratedPattern = Identity and Entity Key = True ?? If not - try that!

That's the default that should be mapped automatically, when that situation existed at the time you created the EDMX model. If you changed your column in SQL Server after you've created the model and you didn't update the model, then you might have a discrepancy that could lead to such errors.