1

I started a new Blazor application and I am trying to use Entity FrameworkCore. I want to link the Identity AspNetUsers table. I want a 1-many relationship with an UserAddress Table. One AspNetUser has many addresses.

 public class UserAddress
   {
    public string Id { get; set; }
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string ZipCode { get; set; }
    ' I don't know what to put here to connect this table with the AspNetUsers Table
      public int UserId {get;set} This doesn't work 
    }

I don't know what to do to have EF construct the 1 to many relation between the AspNetUsers Id and the UserAddress table

wolfeh
  • 666
  • 1
  • 8
  • 23

1 Answers1

5

You can create a one-to-many relationship like this.

UserAddress class:

public class UserAddress
{
    public string Id { get; set; }
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string ZipCode { get; set; }

}

New ApplicationUser inherits Identityuser:

 public class ApplicationUser:IdentityUser
{
    public ICollection<UserAddress> UserAddresses { get; set; }
}

Make changes in your ApplicationDbContext as follows:

 public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }
    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        builder.Entity<ApplicationUser>(b => { b.HasMany(p => p.UserAddresses); }) ;
    }
    public DbSet<UserAddress> UserAddresses { get; set; }
}

Then start the migration and update the database.

Result: enter image description here

Yinqiu
  • 6,609
  • 1
  • 6
  • 14
  • Worked great how would you do a one to one with the Identity AspNetUser table? – wolfeh Sep 29 '20 at 19:39
  • Just replace Icollection in ApplicationUser with UserAddress, and then replace HasMany in context with HasOne. – Yinqiu Sep 30 '20 at 00:16