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

前端 未结 2 1628
旧巷少年郎
旧巷少年郎 2020-12-11 23:10

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          


        
相关标签:
2条回答
  • 2020-12-11 23:29

    You don't need to change mapping code, instead you should change this line:

    lngRequestLineID = 1001233
    

    to this:

    lngRequestLineID = 0
    

    In my expirence decorating de Id entity's property with [KeyAttribute] is enought.

    0 讨论(0)
  • 2020-12-11 23:46

    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");
    }
    }
    
    0 讨论(0)
提交回复
热议问题