Entity Framework Core 连接身份 AspNetUser 表。AspNetUser Id 到自定义表/实体

wol*_*feh 1 asp.net entity-framework asp.net-identity entity-framework-core asp.net-core

我启动了一个新的 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 
    }
Run Code Online (Sandbox Code Playgroud)

我不知道如何让 EF 构建 AspNetUsers Id 和 UserAddress 表之间的一对多关系

Yin*_*qiu 6

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

用户地址类:

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

}
Run Code Online (Sandbox Code Playgroud)

新的ApplicationUser继承Identityuser:

 public class ApplicationUser:IdentityUser
{
    public ICollection<UserAddress> UserAddresses { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

在您的 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; }
}
Run Code Online (Sandbox Code Playgroud)

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

结果: 在此输入图像描述