I have issue with EF code first, when I am trying to insert a new record into a table I receive the 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?
I am using following code:
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();
}
}
And here is my mapping
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");
}
}