Sharing the Users table between an IdentityDbContext, and a main application DbContext c# entity-framework entity-framework-6 sql-server


A single database with two schemas is required for use by my application (written in MVC5/EF6):

  • To store all AspNet identity tables for users and roles. identity
  • To keep all of my general application tables, enter application.

For each schema, I want to utilize a different DbContext, using theidentity creating one using theMicrosoft.AspNet.Identity.EntityFramework.IdentityDbContext<ApplicationUser> assistance class and the primaryapplication one being produced first through the use of code. The main application context is stored in a different assembly so that it may be used in other related projects without having to reference Asp.Net, which is why I have two DbContexts set up in this manner.

But I want to make a reference to a table in theapplication schema/context with a foreign key that I want to add to theidentity.AspNetUsers table, along with a few additional fields. Then, I wish to design aUsers object that maps to the main context in theidentity.AspNetUsers table.

For instance, I'd like anapplication.Tenants which tableidentity.AspNetUsers has a foreign key to, allowing me to have numerous users who are members of a single tenancy.

I believe everything will go smoothly, save for the database creation and perhaps any table-related migrations where I'll have two DbContexts attempting to build the same table.

Can I annotate a table insideOnModelCreating If so, how do I add the foreign key restriction so that it reads as "do not create"? If not, how should I approach this? I don't believe what I'm attempting to do is absurd. Simply put, I don't want two "Users" tables to be connected by an assumed foreign key (i.e. with no actual foreign key constraint).

3/5/2015 4:17:42 PM

Popular Answer

Why do you want to use two differentDbContext s? It would be simpler to have a single context for both your business entities and ASP.NET identity data:

public class DatabaseContext : IdentityDbContext<UserInfo>
    public virtual DbSet<Entity> Entities { get; set; } // Your business entities

    public DatabaseContext()
        : base("name=DatabaseContext")

Observe that theDatabaseContext gains from theIdentityDbContext<UserInfo> .

This strategy comes with some compromises: Your data access layer, for instance, has to referenceMicrosoft.AspNet.Identity.Core and Microsoft.AspNet.Identity.EntityFramework ; yet, if you're utilizing dependency injection or Entity Framework migrations, having a single database context in your project makes things lot simpler.

3/5/2015 4:09:53 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow