Tuesday, February 3, 2015

Stuck trying to modify the ApplicationUser and Multiple DbContexts

When you are trying to update the AccountController in ASP.NET MVC - to enhance the ApplicationUser or another related entity during Registration you may quickly realise that the AccountController doesn't have a DbContext for you to use.

So like anyone, and looking at the other sample controllers you'll probably define something like this:

ApplicationDbContext db = new ApplicationDbContext();
You then write your code, everything compiles and you run a quick test. Suddenly you are left with a strange error... your applications dumps with Entity Framework complaining that about contexts. What's go ?

Well, what happens is within the AccountController there is no mention of a DBContext, instead the DBContext is being brought in using OWIN.

Have a look in Sartup.Auth.cs, in there there is a definition of the ApplicationDbContext:
app.CreatePerOwinContext(ApplicationDbContext.Create);
The UserManager then utilises OWIN to get the instance of the ApplicationDbContext, so when you define your own context the entities that you use to either retrieve or save using your own context will be tracked only within your defined context.

If you want to use the same DbContext as what the UserManager uses then it is as simple as using OWIN to get the context.

var db = HttpContext.GetOwinContext().Get<ApplicationDbContext>();
This gets the DbContext from OWIN and it will be consistent with the DbContext that the UserManager uses.

Please note, if you want to use this method in any other controller other than the AccountController then make sure that you use the using statements:

using Microsoft.AspNet.Identity.Owin;

I hope this helps. I spent hours hunting this one down - hopefully you will find this page and save some time.

0 comments:

Post a Comment