EF core update after migration fails due to nullable type change to enum

0

I'm using EF core 2.2.1 and I'm stuck with the following error when I update to the latest migration:

System.Data.SqlClient.SqlException (0x80131904): Cannot insert the value NULL into column 'CountryCode', table 'context.dbo.User'; column does not allow nulls. UPDATE fails. The statement has been terminated.

The message is clear and due to the change on the entity, before the migration it was:

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
}

then the type of CountryCode changed to an enum (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
}

The entity configuration was not changed even if I tried to set a default value for the enum (still the same error as above):

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
    }
}

The migration is added but the related update fails with this command in the Package Manager Console

dotnet ef database update

The question is how to properly change this type, having in the generated table a not nullable column with default value (the one configured in EF core EntityTypeConfiguration)

c#
asp.net-core
.net-core
entity-framework-core
ef-core-2.2
asked on Stack Overflow Feb 27, 2019 by refex • edited Feb 27, 2019 by refex

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0