简体   繁体   中英

Entity Framework Core: Cannot insert explicit value for identity column in table

I'm using Entity Framework Core, and cannot insert an explicit value for the identity column in table

DBContext:

  modelBuilder.Entity<TbUser>(entity =>
            {
                entity.Property(e => e.Jid)
                    .HasColumnName("JID")
                    .ValueGeneratedOnAdd();
}

TBUser:

        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Jid { get; set; }

In your EF model code, you're defining the column Jid as [DatabaseGenerated(DatabaseGeneratedOption.Identity)]

This tells entity framework that the database will generate a value for this field . Logically then, you should not set the value in code.

If you want to manually set the values in this field you need to remove the DatabaseGenerated decorator above.

Make sure the IDENTITY_INSERT is off. That way the identities for every insert will need to be provided explicitly.

SET IDENTITY_INSERT [ [ database_name . ] schema_name . ] table_name { ON | OFF } 

More details on Identity_insert

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM