Reputation: 686
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
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.
Upvotes: 6