wolfeh
wolfeh

Reputation: 686

Entity Framework Core Join identity AspNetUser table. AspNetUser Id to custom tables/Entities

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

Upvotes: 1

Views: 1725

Answers (1)

Yinqiu
Yinqiu

Reputation: 7190

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

Upvotes: 6

Related Questions