Sharing the Users table between an IdentityDbContext, and a main application DbContext

asp.net-identity c# entity-framework entity-framework-6 sql-server

Question

My application (built in MVC5/EF6) needs to use a single database with two schemas:

  • identity: To store all the AspNet identity tables for users and roles.
  • application: To store all my general application tables.

I want to use a separate DbContext for each schema, with the identity one being created with the Microsoft.AspNet.Identity.EntityFramework.IdentityDbContext<ApplicationUser> helper class, and the main application one being created in code with code first. The reason for having two DbContexts like this is so I can put the main application context in a separate assembly and use it in other related projects without having to reference Asp.Net.

However, I want to reference a table in the application schema/context with a foreign key that I want to add to the identity.AspNetUsers table, along with some other extra fields. I then want to create a Users entity in the main context that maps to the identity.AspNetUsers table.

For example, I want an application.Tenants table of which identity.AspNetUsers has a foreign key to, so that I can have many users belonging to a single tenant.

All this is fine I think and will work with no problems, except when it comes to creating the database, and possibly any migrations that affect that table, as I'll have two DbContext's trying to create the same table.

Can I mark a table within OnModelCreating as "do not create", and if so how do I add the foreign key constraint? If not then how do I handle this? I don't think what I'm trying to do is unreasonable. I just want to avoid having two "Users" tables linked with an implied foreign key (i.e. with no actual foreign key constraint).

1
4
3/5/2015 4:17:42 PM

Popular Answer

Why exactly do you want to use two separate DbContexts? It would be easier to have a single context for both ASP.NET identity data and your business entities:

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

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

Notice that the DatabaseContext inherits from the IdentityDbContext<UserInfo>.

There are some trade-offs with this approach: for example, your data access layer should reference Microsoft.AspNet.Identity.Core and Microsoft.AspNet.Identity.EntityFramework; however, having a single database context in your project makes things much easier if you are using dependency injection or Entity Framework migrations.

2
3/5/2015 4:09:53 PM


Related Questions





Related

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