Replacing automatically created ApplicationDbContext c# entity-framework


I should start by admitting that, despite spending the last hour reading documentation, I'm new to ASP.NET development and don't really grasp database contexts. I decided to have individual user account authentication when I was building my ASP.NET MVC 5 application. Using Visual Studio, a file namedIdentityModels.cs there was a definition of anApplicationUser a class andApplicationDbContext class.

I've been working on some programming, and my CRUD controllers make use ofApplicationDbContext to communicate with the database, each controller must own the following private property:

private ApplicationDbContext db = new ApplicationDbContext();

I then perform the following in the controller actions:

return View(db.Trains.ToList());

I need to comprehend this database context information before I can clean it up. My principal inquiries are:

  1. Is it acceptable for me to use one database context for the duration of my application as I currently do?
  2. Can I swap theApplicationDbContext category defined inIdentityModels.cs by myself?
  3. The ApplicationDbContext the class comes fromIdentityDbContext<ApplicationUser> Does that imply that the user authentication code provided by Visual Studio and my own code should run in separate database contexts?

Using my own database context, named, I believe my ultimate goal is toDatabaseContext This is subsequently applied to a base controller from which all of my controllers inherit. The database context is then only created once, as opposed to within each controller.

Who knows, I might be interpreting this incorrectly. Everyone appears to have their own favored approach to handling things.

I'm grateful.

1/18/2015 1:21:15 PM

Accepted Answer

Is it okay to use just one database context for my entire application, like I'm doing now?

  • It is acceptable if you have opted to access the database directly from the user interface layer (which is the subject of a separate discussion).ApplicationDbContext is a private field of your controller, and controllers are made and removed at the request of the user.ApplicationDbContext will be created and disposed per request.

Can I replace the ApplicationDbContext class defined in IdentityModels.cs with my own?

  • You can do it without a doubt. It is utilized to develop aUserStore which is recievedDbContext as a constructor argument, so this

var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(new CustomDbContext("connection")));

will function You must nevertheless ensure thatApplicationUser is a thing in your particular situation. Of course you may replace or overrideApplicationUser and also

The ApplicationDbContext class derives from IdentityDbContext, does that mean I should have seperate database contexts for my user authentication stuff provided by Visual Studio, and my own code?

Asp.Net Identity automatically creates a new database for you andApplicationDbContext adapted to operate with this data base. The only requirement is that all relevant tables be present. You can store your entities related to authentication in any other data base. To use the same context throughout, you can expand this database to include other tables that you use in your application.

P.S:ApplicationDbContext not required to implementIdentityDbContext<ApplicationUser> Extension of a DefaultDbContext works equally well (to make the following work, you must utilize code migrations if you already generated a database):

 public class ApplicationDbContext : DbContext 
     public ApplicationDbContext()
         : base("DefaultConnection")

     public static ApplicationDbContext Create()
         return new ApplicationDbContext();
1/18/2015 3:31:04 PM

Popular Answer

You could want to design your own unique authentication database for login authentication, in my opinion. You must meticulously adhere to the directions provided. 1) In order to implement unique authentication, you must design your own class. for instance, I'm setting up the following student class. This class can be created under the MVC MODEL section.

class student{
public int rollno{get;set;}
public string firstName{get;set;}
public string lastName{get;set;}

2) You will now use identityDbContext to construct your own dbcontext for the student class. This class can be created under the App Start section.

public class ApplicationDbContext : IdentityDbContext<student>
        public ApplicationDbContext() : base()


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

3) You may now use it at home in the controller as shown.

public class HomeController : Controller
        // GET: Home
        public async Task<ActionResult> Index()
            var context = new ApplicationDbContext(); // DefaultConnection
            var store = new UserStore<student>(context);
            var manager = new UserManager<student>(store);
            var signInManager = new SignInManager<student, string>(manager,
            var username  = "Edward";
            var email = "";
            var password = "Your password";
            var user = await manager.FindByEmailAsync(email);

            if (user == null)
                user = new student                    {
                    UserName = username,//username ,Email are getting from identityDbContext and the other three RollNO,FirstName and LastName are your own Custom like this you can extend your any kind of data you like add or extend with IdentityDbContext.
                    Email = email,
                    RollNo = "15",
                    FirstName = "David",
                    LastName = "Kandel"

                await manager.CreateAsync(user, password);
                var result = await signInManager.PasswordSignInAsync(user.UserName, password, true, false);

                if (result == SignInStatus.Success)
                    return Content("Hello, " +user.rollno + ""  + user.FirstName + " " + user.LastName);


            return Content("Hello, Index");

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow