本文介绍了首先EF代码:当IDENTITY_INSERT设置为OFF时,无法为表''中的标识列插入显式值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我首先遇到EF代码问题
I have issue with EF code first
当我尝试将新记录插入到表中时,我会收到消息。
when I am trying to insert new record into table I recieve message.
Cannot insert explicit value for identity column in table '' when IDENTITY_INSERT is set to OFF.
有人知道我为什么要出错吗?
Any idea why I am getting the error?
我正在使用以下代码:
public void SaveNewResponse()
{
using (var context = new Context())
{
var newResponse = new Response()
{
lngRequestLineID = 1001233,
memXMLResponse = "test Response",
fAdhoc = false,
};
context.tblResponses.Add(newResponse);
context.SaveChanges();
}
}
这是我的映射
public class tblResponsMap : EntityTypeConfiguration<tblRespons>
{
public tblResponsMap()
{
// Primary Key
this.HasKey(t => new { t.lngResponseLineID});
// Properties
this.Property(t => t.lngResponseLineID)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
this.Property(t => t.lngRequestLineID);
// Table & Column Mappings
this.ToTable("tblResponses");
this.Property(t => t.lngResponseLineID).HasColumnName("lngResponseLineID");
this.Property(t => t.lngRequestLineID).HasColumnName("lngRequestLineID");
this.Property(t => t.fAdhoc).HasColumnName("fAdhoc");
this.Property(t => t.memXMLResponse).HasColumnName("memXMLResponse");
}
}
推荐答案
好吧,
我找到了。
数据库已正确设置,但我的映射不正确。
Ok,I have found it.The database has been set up correctly, but my mapping has been incorrect.
public class tblResponsMap : EntityTypeConfiguration<tblRespons>
{
public tblResponsMap()
{
// Primary Key
this.HasKey(t => new { t.lngResponseLineID});
// Properties
this.Property(t => t.lngResponseLineID)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); <-- here
this.Property(t => t.lngRequestLineID);
// Table & Column Mappings
this.ToTable("tblResponses");
this.Property(t => t.lngResponseLineID).HasColumnName("lngResponseLineID");
this.Property(t => t.lngRequestLineID).HasColumnName("lngRequestLineID");
this.Property(t => t.fAdhoc).HasColumnName("fAdhoc");
this.Property(t => t.memXMLResponse).HasColumnName("memXMLResponse");
}
}
这篇关于首先EF代码:当IDENTITY_INSERT设置为OFF时,无法为表''中的标识列插入显式值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!