本文介绍了实体框架IDENTITY_INSERT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The 'Category' table in database defined like this:

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

我要插入新数据: p>

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();

我收到错误:

但是我没有插入CategoryID!我想要它接收自动值!

But I am not inserting the CategoryID! I want it to receive auto value!

推荐答案

在我的情况下,您的方案工作正常 - 使用EF4。

Your scenario works just fine in my case - using EF4.

检查以下内容:


  • 您是否更改了数据库模型,因为您首先创建了您的实体模型,如果是,您真的更新了您的实体模型?

  • have you changed your database model since you first created your Entity model, and if so, have you really updated your entity model??

是您的 cat.EntityState 真的分离在那个时间点?在我的情况下,当使用具有 ObjectContext 的EF4时,它是添加。在这种情况下,您不会将新的 Cat 对象添加到类别集合..

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

这篇关于实体框架IDENTITY_INSERT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 17:00