entity frameworkIDENTITY_INSERT

数据库中的“类别”表定义如下:

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

我想插入新数据:

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

我收到错误:

当IDENTITY_INSERT设置为OFF时,无法在表’Categories’中为identity列插入显式值。

但我没有插入CategoryID! 我希望它能获得自动价值!

您的方案在我的情况下运行正常 – 使用EF4。

检查以下事项:

  • 你是否在第一次创建实体模型后更改了数据库模型,如果是这样,你真的更新了实体模型吗?

  • 是你的cat.EntityState在那个时间cat.EntityState真的detached了? 在我的例子中,当使用带有ObjectContext EF4时,它是Added 。 在这种情况下,您不会将新的Cat对象添加到类别集合中。

你的映射是错误的。 StoreGeneratedPattern上的StoreGeneratedPattern 设置为Identity ,但您将其设置为None 。 修复它。