My application (built in MVC5/EF6) needs to use a single database with two schemas:
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).
Why exactly do you want to use two separate DbContext
s? 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With