0

I have extend the ApplicationUser class in the template models to include an optional Company:

public class ApplicationUser : IdentityUser
{
    public virtual Guid? CompanyID { get; set; }

    public virtual Company Company { get; set; }
}

And in the 'Company' class I've included a collection of ApplicationUsers:

    [Required]
    [Key]
    public Guid? CompanyId { get; set; }

    public virtual ICollection<ApplicationUser> Users { get; set; }

Do I also need to specify the relation in the ModelBuilder for the ApplicationdbContext? or should Code-First handle this for me?

I ask because when I grab _context.Users.ToList() in a controller Company is always null, even if CompanyID is populated for the ApplicationUser.

CodeNotFound
  • 22,153
  • 10
  • 68
  • 69
jidl
  • 195
  • 1
  • 2
  • 19

1 Answers1

1

Change Model To It:

[Required]
[Key]
public Guid CompanyId { get; set; }
public virtual ICollection<ApplicationUser> Users { get; set; }

And Config MolderBinder For ApplicationUser To this:

modelBuilder.Entity<ApplicationUser>().HasOptional(row => row.Company ).WithMany().HasForeignKey(row => row.CompanyID ).WillCascadeOnDelete(false);
Reza Bahari
  • 104
  • 7