IDENTITY INSERT in Entity Framework

c# entity-framework

Question

The 'Category' table in database defined like this:

CategoryID - PK ,identity specification ON  (only this column has identity)   
Description  
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!

1
3
12/24/2012 10:45:12 PM

Accepted Answer

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..

4
1/12/2011 9:30:36 PM

Popular Answer

Your mapping is wrong. The StoreGeneratedPattern on CategoryID should be set to Identity, but you have it set to None. Fix that.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow