首页 > 解决方案 > Entity Framework Core Join 标识 AspNetUser 表。自定义表/实体的 AspNetUser Id

问题描述

我启动了一个新的 Blazor 应用程序,并尝试使用 Entity FrameworkCore。我想链接 Identity AspNetUsers 表。我想要一个与 UserAddress 表的一对多关系。一个 AspNetUser 有多个地址。

 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 
    }

我不知道该怎么做才能让 EF 构建 AspNetUsers Id 和 UserAddress 表之间的一对多关系

标签: asp.netentity-frameworkasp.net-coreentity-framework-coreasp.net-identity

解决方案


您可以像这样创建一对多的关系。

用户地址类:

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

}

新的 ApplicationUser 继承 Identityuser:

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

在 ApplicationDbContext 中进行如下更改:

 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; }
}

然后开始迁移并更新数据库。

结果: 在此处输入图像描述


推荐阅读