异常无法在 table 中为标识列插入显式值

Exception Cannot insert explicit value for identity column in table

使用FluentAPI我是autoincreamenting我Table的主键。

FluentAPI配置如下:

mb.ToTable("StationeryItems");
builder.HasKey(c => c.StationeryItemId);

我得到的异常:

Cannot insert explicit value for identity column in table 'StationeryItems' when IDENTITY_INSERT is set to OFF.

尝试以下方法之一,也许它们可以解决您的问题。 DatabaseGeneratedOption:

[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int StationeryItemId { get; set; }

或者:

builder.Entity<StationeryItems>().Property(t => t.StationeryItemId) 
        .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

在 EF Core 中:

builder.Entity<StationeryItems>().Property(b => b.StationeryItemId).ValueGeneratedOnAdd();