IDENTITY INSERT in Entity Framework

c# entity-framework

Question

The database's "Category" table is described as follows:

CategoryID - PK ,identity specification ON  (only this column has identity)   
Description  
Title  

I wish to add fresh data:

Category cat = new Category
{
    Description = "xxx",
    Title = "yyy",
};
if (cat.EntityState == EntityState.Detached)
{
   Articlerctx.AddToCategories(cat);
}
return Articlerctx.SaveChanges();

I experience a problem:

Cannot insert explicit value for identity column in table 'Categories' when IDENTITY_INSERT is set to OFF.

However, I'm not adding the CategoryID! It should get automatic value, please!

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

Accepted Answer

Using EF4, your scenario runs well in my case.

Verify the following details:

  • Has your entity model really been altered since you initially developed it, and if so, has your database model changed since then?

  • are youcat.EntityState really detached when that happened? In my situation, EF4 with anObjectContext , it isAdded . Consequently, you wouldn't be included the newCat item in the collection of categories.

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

Popular Answer

Your map is incorrect. TheStoreGeneratedPattern on CategoryID Set should toIdentity yet you've had it set toNone Correct 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