Code to follow. Is there a way to set the Application User : Identity custom foreign key to nullable : false using model builder net core?
Here is my application user class:
public class ApplicationUser : IdentityUser
{
[Required]
public Company Company { get; set; }
[Required]
public int CompanyId { get; set; }
}
Followed by the custom class:
public class Company : AuditableEntity
{
[Key]
public int CompanyId { get; set; }
[Required]
public string CompanyName { get; set; }
[Required]
public string EmailAddress { get; set; }
[Required]
public string PhoneNumber { get; set; }
public IEnumerable<ApplicationUser> ApplicationUsers { get; set; }
}
With model builder:
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<ApplicationUser>()
.HasOne(p => p.Company)
.WithMany(b => b.ApplicationUsers)
.OnDelete(DeleteBehavior.Cascade)
.IsRequired()
.HasForeignKey(p => p.CompanyId);
builder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
base.OnModelCreating(builder);
}
With resulting migration:
migrationBuilder.CreateTable(
name: "AspNetUsers",
columns: table => new
{
Id = table.Column<string>(nullable: false),
UserName = table.Column<string>(maxLength: 256, nullable: true),
NormalizedUserName = table.Column<string>(maxLength: 256, nullable: true),
Email = table.Column<string>(maxLength: 256, nullable: true),
NormalizedEmail = table.Column<string>(maxLength: 256, nullable: true),
EmailConfirmed = table.Column<bool>(nullable: false),
PasswordHash = table.Column<string>(nullable: true),
SecurityStamp = table.Column<string>(nullable: true),
ConcurrencyStamp = table.Column<string>(nullable: true),
PhoneNumber = table.Column<string>(nullable: true),
PhoneNumberConfirmed = table.Column<bool>(nullable: false),
TwoFactorEnabled = table.Column<bool>(nullable: false),
LockoutEnd = table.Column<DateTimeOffset>(nullable: true),
LockoutEnabled = table.Column<bool>(nullable: false),
AccessFailedCount = table.Column<int>(nullable: false),
Discriminator = table.Column<string>(nullable: false),
CompanyId = table.Column<int>(nullable: true) // NOTE NULLABLE HERE
}
I've been searching through similar issues across previous questions, however I have yet to come across a solution/explanation. Any ideas?
Appreciate your time in advance.