Tag: entity framework

Customizing ApplicationDbContext in ASP.NET MVC 5 and ASP.NET Identity 2.0

As of Visual Studio 2013 Update 1, the ASP.NET MVC 5 templates with Authentication enabled will create a project that contains a class named ApplicationDbContext. This is the Entity Framework DbContext that is used by the ASP.NET Identity libraries to manage user records.

By default, here is the generated class:

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

You’ll notice that it inherits from IdentityDbContext with a generic type of ApplicationUser. The base DbContext handles whatever is needed by the ASP.NET Identity libraries, and the ApplicationUser is the model that describes the authenticated user. If you’re like me, and you don’t want to create a ton of separate DbContext classes for different repositories, you can just mash it all together into ApplicationDbContext like so.

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

    public DbSet<BlogBlogs { get; set; }
    public DbSet<PostPosts { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        // do fluent API stuff below
    }
}

At a glance, it seems weird that a DbContext which is inherited from a very specific library contains other non-related DbSet objects, but it gets the job done. If you’re more into separation of concerns and don’t want a huge explosion of fluent API in a single class, look into creating separate DbContext classes as appropriate. Just remember that you need to maintain a connection string per DbContext in your web.config.… Read more