【发布时间】:2020-07-11 12:31:13
【问题描述】:
我使用 PostgreSql 作为我的数据库。我正在尝试向用户表添加一个外键,但不是创建一个重复的 IdentityUser 表。
我为ApplicationDbContext 继承了IdentityDbContext<IdentityUser>,其代码为:
public class ApplicationDbContext : IdentityDbContext<IdentityUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}
}
这可以将所有表创建为:
我正在尝试创建一个用户是外键的模型:
public class AccountModel
{
[Key]
public string Id { get; set; } = Guid.NewGuid().ToString();
public string AccountName { get; set; }
public string AccountNumber { get; set; }
public BankModel BankDetails { get; set; }
public IdentityUser User { get; set; }
}
它的 DBContext 是
public class AccountDbContext: DbContext
{
public AccountDbContext(DbContextOptions<AccountDbContext> options) : base(options)
{
}
public DbSet<AccountModel> Accounts { get; set; }
public DbSet<BankModel> Banks { get; set; }
}
查看帖子 - https://stackoverflow.com/a/41275590/3782963,接受的答案使用 ApplicationUser,我认为这与 IdentityUser 类似,当我进行迁移时,它没有向 AspNetUsers 添加 FK,而是创建了一个名为IdentityUser 然后将一个 FK 添加到这个新创建的表中。看起来像:
我不确定我做错了什么。救命!
更新
我也用 Azure SQL Server 尝试了这段代码,但它仍然给了我同样的问题。另外,我添加了[ForeignKey("AspNetUser")]
public class AccountModel
{
[Key]
public string Id { get; set; } = Guid.NewGuid().ToString();
public string AccountName { get; set; }
public string AccountNumber { get; set; }
public BankModel BankDetails { get; set; }
[ForeignKey("AspNetUsers")]
public IdentityUser User { get; set; }
}
我仍然遇到同样的问题。
更新 2
这种关系存在于两个不同的上下文之间,即ApplicationDbContext 和AccountDbContext。将 public DbSet<AccountModel> Accounts { get; set; } 添加到 ApplicationDbContext 可以正常工作并自动添加 FK 关系。
【问题讨论】:
标签: c# asp.net-mvc asp.net-core entity-framework-core asp.net-identity