标识插入和LINQ to SQL [英] IDENTITY INSERT and LINQ to SQL
问题描述
我有一个SQL Server数据库。这个数据库有一个名为项目表。项目有一个名为ID的属性。 ID是我的表的主键。这个主键是1增量值的int当我尝试插入记录,我收到一个错误,说:
I have a SQL Server database. This database has a table called Item. Item has a property called "ID". ID is the primary key on my table. This primary key is an int with an increment value of 1. When I attempt to insert the record, I receive an error that says:
不能插入在表'产品'标识列显式值时IDENTITY_INSERT设置为OFF。
Cannot insert explicit value for identity column in table 'Item' when IDENTITY_INSERT is set to OFF.".
我试图插入使用下面的code记录:
I am attempting to insert records using the following code:
public int AddItem(Item i)
{
try
{
int id = 0;
using (DatabaseContext context = new DatabaseContext())
{
i.CreatedOn = DateTime.UtcNow;
context.Items.InsertOnSubmit(i);
context.SubmitChanges();
id = i.ID;
}
return id;
}
catch (Exception e)
{
LogException(e);
}
}
当我看着i.ID提交前,我注意到i.ID设置为0,这将意味着我试图插入0的身份。但是,我不知道它应该是什么。有人可以帮我吗?
When I look at i.ID before submitting it, I notice that i.ID is set to 0. Which would imply that I'm trying to insert 0 as the identity. However, I'm not sure what it should be. Can someone help me out?
谢谢!
推荐答案
这听起来简单,就好像你的模型是不知道的事实,它的是的身份;在 ID
列应标记为DB-产生的(自动生成的值
在UI,或 IsDbGenerated
的XML),并可能作为主键。然后,它不会尝试插入,然后将更新它写入后正确的值。
It sounds simply as though your model is unaware of the fact that it is an identity; the ID
column should be marked as db-generated (Auto Generated Value
in the UI, or IsDbGenerated
in the xml), and probably as the primary key. Then it will not attempt to insert it, and will update the value correctly after it is written.
这篇关于标识插入和LINQ to SQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!