开发者

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 really detached at that point in time?? In my case, when using EF4 with an ObjectContext, it is Added. In that case, you wouldn't be adding the new Cat object to the categories collection..

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜