Entity framework IDENTITY_INSERT
The 'Category' table in database defined like this:
CategoryID - PK ,identity specification ON (only this column has identity)
D开发者_JAVA百科escription
Title
I want to insert new data:
Category cat = new Category
{
Description = "xxx",
Title = "yyy",
};
if (cat.EntityState == EntityState.Detached)
{
Articlerctx.AddToCategories(cat);
}
return Articlerctx.SaveChanges();
I get error:
Cannot insert explicit value for identity column in table 'Categories' when IDENTITY_INSERT is set to OFF.
But I am not inserting the CategoryID! I want it to receive auto value!
Your mapping is wrong. The StoreGeneratedPattern
on CategoryID
should be set to Identity
, but you have it set to None
. Fix that.
Your scenario works just fine in my case - using EF4.
Check the following things:
have you changed your database model since you first created your Entity model, and if so, have you really updated your entity model??
is your
cat.EntityState
reallydetached
at that point in time?? In my case, when using EF4 with anObjectContext
, it isAdded
. In that case, you wouldn't be adding the newCat
object to the categories collection..
精彩评论