【发布时间】:2011-04-23 02:19:54
【问题描述】:
我正在尝试通过 LINQ 将一些内容写入我的数据库。目前,我收到以下错误:
Cannot insert explicit value for identity column in table 'MyTable' when IDENTITY_INSERT is set to OFF.
我了解这是与主键相关的问题。我的表将身份规范设置为“是”,身份增量设置为“1”。但我已经使用如下代码成功更新了其他表:
using (DataModelDataContext context = new DataModelDataContext())
{
List<MyTable> newRecords = new List<MyTable>();
MyTable record1 = new MyTable();
record1.CreatedBy = GetUserName();
record1.Information = GetInformation();
newRecords.Add(record1);
MyTable record2 = new MyTable();
record2.CreatedBy = GetUserName();
record2.Information = GetInformation();
newRecords.Add(record2);
context.MyTables.InsertAllOnSubmit(newRecords);
context.SubmitChanges();
}
什么会导致这个错误?如果我想写新记录,有没有办法在发送到数据库之前设置主键?像“GetNextKey()”之类的东西?基本上,我只需要插入这些记录。我做错了什么?
谢谢!
【问题讨论】: