I am using PostgreSql as my DB. I am trying to add a foreign key to the user's table but instead of that a duplicate IdentityUser
table is being created.
I have inherited IdentityDbContext<IdentityUser>
for ApplicationDbContext
whose code is:
public class ApplicationDbContext : IdentityDbContext<IdentityUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}
}
This is able to create all the tables as:
I am trying to create a model where the user is the foreign key by doing:
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; }
}
And it's DBContext is
public class AccountDbContext: DbContext
{
public AccountDbContext(DbContextOptions<AccountDbContext> options) : base(options)
{
}
public DbSet<AccountModel> Accounts { get; set; }
public DbSet<BankModel> Banks { get; set; }
}
Looking at the post - https://stackoverflow.com/a/41275590/3782963, the accepted answer uses ApplicationUser
which I believe is similar to IdentityUser
, when I do the migrations, instead of adding an FK to AspNetUsers
it creates a new table called IdentityUser
and then an FK is added to this newly created table. Which looks like:
I am not sure what I am doing wrong. Help!
Update
I tried this code with Azure SQL Server too and it still gave me the same problem. Also, I added [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; }
}
I still get the same problem.
Update 2
The relationship is between two different contexts, i.e. ApplicationDbContext
and AccountDbContext
. Adding public DbSet<AccountModel> Accounts { get; set; }
to ApplicationDbContext
works fine and automatically adds an FK relationship.
You need to define the relationship between AccountModel
and IdentityUser
in your model builder.
Something along the lines of
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<AccountModel>()
.HasOne(accountModel=> accountModel.User);
base.OnModelCreating(builder);
}
See here for info on single navigation property and foreign keys.