Mark
Mark

Reputation: 7818

Merge DBContext and IdentityDbContext

Is it possible to merge the DBContext and the IdentityDbContext - enable migrations, and then manage code first updates to my database, using one update statement?

ie. in my IdentityModels.cs file I have:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("tbConn", throwIfV1Schema: false)
    {
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
}

And in my tbContext.cs file (which was created when I added model classes) I have:

namespace tb.Models
{
public class tbContext : DbContext
{
    public tbContext() : base("name=tbConn")
    {
        Database.SetInitializer<tbContext>(new tbInitializer<tbContext>());
    }
    public System.Data.Entity.DbSet<tb.Models.Tour> Tours { get; set; }
}
}

public class tbInitializer<T> : DropCreateDatabaseAlways<tbContext>
{
    protected override void Seed(tbContext context)
    {
        ApplicationDbContext userscontext = new ApplicationDbContext();
        var userStore = new UserStore<ApplicationUser>(userscontext);
        var userManager = new UserManager<ApplicationUser>(userStore);

        // Create user
        if (!userscontext.Users.Any(x => x.UserName == "marktest"))
        { var user = new ApplicationUser { UserName = "marktest", Email = "[email protected]" }; userManager.Create(user, "Pa$$w0rd!");}

        var tour = new List<Tour>
        { // seed database code };
        tour.ForEach(s => context.Tours.Add(s));
        context.SaveChanges();
    }
}

Is there any way I can merge these two contexts, so I only have one database, and one context to manage?

Thanks for any help,

Mark

Upvotes: 2

Views: 3947

Answers (1)

webformer
webformer

Reputation: 136

IdentityDbContext is inheriting from DBContext by default. There is no need of creating a new context (in your case tbContext) - just cut and paste the ApplicationDbContext from the IdentityModels.cs and put it to your data layer.

Upvotes: 7

Related Questions