Home > Software engineering >  Make IdentityUser.PhoneNumber nullable
Make IdentityUser.PhoneNumber nullable

Time:07-13

Im trying to make PhoneNumber nullable for my IdentityUser model, but its not working. I have this User class

public class User : IdentityUser<Guid> 
{
    ...props
}

I tried adding it in my Context like:

public class DbContext: IdentityContext<User, Role, Guid>
{
    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        ConfigureUserTable(builder);
    }

    private void ConfigureUserTable(ModelBuilder builder)
    {
        builder.Entity<User>
            .Property(x => x.PhoneNumber)
            .IsRequired(false);
    }
}

but when I created a new migration, nothing changed in the new migration.

Also tried to override like:

public class User : IdentityUser<Guid> 
{
    public override string? PhoneNumber { get; set; }
    ...props
}

But still nothing in the new migration.

How can I make PhoneNumber optional on DB without creating a new migration and updating the field by writing explicit SQL?

CodePudding user response:

It seems like the problem was that someone went and made the column on DB not nullable manually. Because of that, nothing new was generated when I was running migrations.

CodePudding user response:

Based on your answer, it looks like you had a situation related to your environment. In case you are new to migrations, it's SUPER important that you don't make direct database modifications to any tables handled by EF Migrations. You can get naming conventions out of sync, or in your case, migrations that just don't appear to do what you need to.

Entity Framework, although appears like it "checks to see if the model matches", what it's really doing is checking to see if the last applied migration matches the ones it thinks it needs to run. To Date, I don't think there is a way to have EF validate every single field during a migration add.

Just something to be aware of. If you have DBAs who don't want modifications made directly, use the new migration bundles for deployment or script them.

Deployments of EF Migrations Reference

  • Related