EF Core Fluent API PK非自动增量

时间:2019-06-09 22:35:48

标签: entity-framework entity-framework-core auto-increment

我使用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 &#x27;UserSettings&#x27; when IDENTITY_INSERT is set to OFF.

怎么了?

0 个答案:

没有答案