Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
556 views
in Technique[技术] by (71.8m points)

sql server 2000 - EF code first: Cannot insert explicit value for identity column in table '' when IDENTITY_INSERT is set to OFF

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?

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

    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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");
}
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...