我使用EF Core,并且不想具有自动增量PK。我使用Fluent API。我的代码:
public class UserSetting
{
public int UserId { get; set; }
public string TemplateName { get; set; }
public string PrimaryColor { get; set; }
public string SecondaryColor { get; set; }
public string TextColor { get; set; }
public string BackgroundColor { get; set; }
public string ShadeColor { get; set; }
}
public class UserSettingMap : IEntityTypeConfiguration<UserSetting>
{
public void Configure(EntityTypeBuilder<UserSetting> builder)
{
builder.HasKey(p => p.UserId);
builder.Property(c => c.UserId)
.ValueGeneratedNever()
.HasAnnotation("DatabaseGenerated", DatabaseGeneratedOption.None);
}
}
但是迁移有非常有趣的代码:
public partial class UserSettingPKNonAutoincrement : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<int>(
name: "UserId",
table: "UserSettings",
nullable: false,
oldClrType: typeof(int))
.OldAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<int>(
name: "UserId",
table: "UserSettings",
nullable: false,
oldClrType: typeof(int))
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
}
}
因此,OldAnnotation和Annotation相同。为什么这样?
执行迁移后,我看到了UserId
的autoincrement属性,当然,不能用我的UserId
值添加记录:
SqlException: Cannot insert explicit value for identity column in table 'UserSettings' when IDENTITY_INSERT is set to OFF.
怎么了?