0

我正在使用 EF core 2.2.1,当我更新到最新迁移时遇到以下错误:

System.Data.SqlClient.SqlException(0x80131904):无法将值 NULL 插入列“CountryCode”、表“context.dbo.User”;列不允许空值。更新失败。该语句已终止。

该消息很清楚,并且由于实体的更改,在迁移之前它是:

public class RegistrationUser : IHaveId, ISearchable
{
    public int Id { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int? CountryCode { get; set; }
    // other properties
}

然后 CountryCode 的类型更改为枚举 (CountryCode)

public class RegistrationUser : IHaveId, ISearchable
{
    public int Id { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public CountryCode CountryCode { get; set; }
    // other properties
}

即使我尝试为枚举设置默认值,实体配置也没有改变(仍然与上面相同的错误):

public class UserConfiguration: IEntityTypeConfiguration<User>
{
    public void Configure(EntityTypeBuilder<User> builder)
    {
        builder.HasKey(e => e.Id);
        builder.Property(e => e.Id)
            .HasColumnName("Id").ValueGeneratedOnAdd();
        builder.Property(e => e.Email).HasMaxLength(250);
        builder.Property(e => e.Password).HasMaxLength(250);
        builder.Property(e => e.FirstName).HasMaxLength(100);
        builder.Property(e => e.LastName).HasMaxLength(100);
        builder.Property(e => e.CountryCode).HasDefaultValue(CountryCode.Unknown);
        // other configurations
    }
}

已添加迁移,但相关更新在包管理器控制台中使用此命令失败

dotnet ef 数据库更新

问题是如何正确更改此类型,在生成的表中具有默认值的不可为空的列(在 EF 核心 EntityTypeConfiguration 中配置的列)

4

0 回答 0