Cross context foreign key in EntityFramework core

Viewed 160

I am trying to do a cross-context foreign key reference, but it's not working.

I have two DbContexts, ApplicationDbContext and BankDbContext. ApplicationDbContext has:

public class ApplicationDbContext : IdentityDbContext<IdentityUser>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
    }
}

BankDbContext has:

public class AccountDbContext: DbContext
{
    public AccountDbContext(DbContextOptions<AccountDbContext> options) : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
    }

    public DbSet<AccountModel> Accounts { get; set; }
}

And the AccountModel has:

public class AccountModel
{
    [Key]
    public string Id { get; set; } = Guid.NewGuid().ToString();

    public string AccountName { get; set; }

    public string AccountNumber { get; set; }

    public string UserId { get; set; }

    public virtual IdentityUser User { get; set; }
}

ApplicationDbContext creates many tables; one of them is AspNetUsers (it saves the user details). When I update the table with the new migrations, it creates all the tables from ApplicationDbContext and AccountModel table, but for some reason, it also creates IdentityUser table. This shouldn't happen because ApplicationDbContext already creates one.

I tried adding ForeignKey["AspNetUsers"] attribute annotation on top of public virtual IdentityUser User { get; set; }, but it still creates that table.

the above code will work when I add Accounts DbSet to ApplicationDbContext, like this:

public class ApplicationDbContext : IdentityDbContext<IdentityUser>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
    }
    public DbSet<AccountModel> Accounts { get; set; }
}

In a nutshell, I am trying to add a reference from one context to another on the same database, but it just creates duplicate tables with different names. Any help on this is appreciated.

0 Answers
Related