Carlos Martinez
Carlos Martinez

Reputation: 4510

Extending ASP.NET Identity 2.0

I'm having trouble understanding the whole ASP.Net Identity framework, I first tried integrating Identity 1.0 to an existing application, but I ended up with 2 DbContext classes, my application data was on MyDbContext, and Identity user data on IdentityDbContext.

I want to use a single DbContext for both my application data and Identity related data, and I found on a different question that I can use IdentityDbContext just as I use DbContext; however, I think I'm missing something.

I'm using the sample project from the Identity team

PM> Install-Package Microsoft.AspNet.Identity.Samples -Pre

and tried to insert DbSet properties to the ApplicationDbContext

 public class ApplicationDbContext : IdentityDbContext
{
    public ApplicationDbContext()
        : base("DefaultConnection")
    {
    }

    static ApplicationDbContext()
    {
        // Set the database intializer which is run once during application start
        // This seeds the database with admin user credentials and admin role
        Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer());
    }

    public virtual DbSet<Student> students { get; set; }
    public virtual DbSet<Teachers> teachers { get; set; }

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

I'm using the ApplicationDbInitializer seed method to populate those 2 tables, something like this:

Student s = new Student { Name = "John" ... };
db.students.Add(s);
db.SaveChanges();

But EF doesn't seem to create those 2 tables, and the seed method is not being called, what is going on?

EDIT:

Well, I needed to run code that uses the database for EF to drop and recreate the database.

Is there any overhead in using IdentityDbContext to manage all my application data? What is the difference between using IdentityDbContext and using the generic version IdentityDbContext<IdentityUser>?

Upvotes: 8

Views: 1444

Answers (1)

Tobias
Tobias

Reputation: 2840

In most cases, using only one Entity Framework context is preferred, since then, you'll only have to manage that single one, which means less overhead.

The difference between the two is that IdentityDbContext is simply a class that derives from DbContext (like you would when making your own), but it contains additional DbSets that deals with authentication, so you don't have to implement it yourself. Deriving from IdentityDbContext is fine. For more information, you can have a look at the documentation.

Upvotes: 5

Related Questions