In ASP.NET Core IdentityDbContext, I am using EF Code First. I have:
public class DDMDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, long, IdentityUserClaim<long>, ApplicationUserRole, IdentityUserLogin<long>, IdentityRoleClaim<long>, IdentityUserToken<long>>
{
public DDMDbContext(DbContextOptions<DDMDbContext> options)
: base(options) { }
public virtual DbSet<ApplicationRole> ApplicationRole { get; set; }
public virtual DbSet<ApplicationUserRole> ApplicationUserRole { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ApplicationUserRole>(userRole =>
{
userRole.HasKey(ur => new { ur.UserId, ur.RoleId });
userRole.HasOne(ur => ur.Role)
.WithMany(r => r.UserRoles)
.HasForeignKey(ur => ur.RoleId)
.IsRequired();
userRole.HasOne(ur => ur.User)
.WithMany(r => r.UserRoles)
.HasForeignKey(ur => ur.UserId)
.IsRequired();
});
}
}
namespace DDM.API.Core.Data.Identity
{
public class ApplicationUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public ICollection<ApplicationUserRole> UserRoles { get; set; }
}
public class ApplicationRole : IdentityRole
{
public ICollection<ApplicationUserRole> UserRoles { get; set; }
}
public class ApplicationUserRole : IdentityUserRole<long>
{
public virtual ApplicationUser User { get; set; }
public virtual ApplicationRole Role { get; set; }
}
}
I found that in ApplicationUser, these fields are required.:
EmailConfirmed
PhoneNumberConfirmed
TwoFactorEnabled
LockoutEnabled
AccessFailedCount
I tried to use:
entity.Property(m => m.EmailConfirmed).IsRequired(false);
entity.Property(m => m.PhoneNumberConfirmed).IsRequired(false);
entity.Property(m => m.TwoFactorEnabled).IsRequired(false);
entity.Property(m => m.LockoutEnabled).IsRequired(false);
entity.Property(m => m.AccessFailedCount).IsRequired(false);
But got error:
The property ‘ApplicationUser.EmailConfirmed’ cannot be marked as nullable/optional because the type of the property is ‘bool’ which is not a nullable type. Any property can be marked as non-nullable/required, but only properties of nullable types can be marked as nullable/optional.
How do I change these fields to Not Required?
Thanks
>Solution :
You should leave those properties as they are, just ignore them for sign in, lockout, etc. Check this article: https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity-configuration?view=aspnetcore-6.0
So, for Sign-In you could use:
services.Configure<IdentityOptions>(options =>
{
// Default SignIn settings.
options.SignIn.RequireConfirmedEmail = false;
options.SignIn.RequireConfirmedPhoneNumber = false;
});
And rest of properties could be ignored by similar logic.