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:

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.

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.

Comments 1

  • Thanks a lot. It is always good to find some help that is exactly what I need. I didn’t want to create separate DbContext classes and I did want to keep the pre generated login schema. I had already changed the default Db from “Base (“default”, to :Base (“CDDB”, for my production Db on the server so your solution is perfect got me.

Leave a Reply

Your email address will not be published. Required fields are marked *