Replacing automatically created ApplicationDbContext

asp.net asp.net-mvc c# entity-framework

Question

I should preface this with a disclaimer saying I'm new to ASP.NET development and don't really understand database contexts, despite spending the last hour reading documentation. When I built my ASP.NET MVC 5 application I chose to have individual user account authentication. Visual Studio created a file called IdentityModels.cs, and within there it defined an ApplicationUser class and a ApplicationDbContext class.

I've done some development work, and my CRUD controllers use ApplicationDbContext to talk to the database, by having this private property on every controller:

private ApplicationDbContext db = new ApplicationDbContext();

In the controller actions I then do things like:

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

I want to tidy this database context stuff up, but I need to understand it first. My main questions are:

  1. Is it okay to use just one database context for my entire application, like I'm doing now?
  2. Can I replace the ApplicationDbContext class defined in IdentityModels.cs with my own?
  3. The ApplicationDbContext class derives from IdentityDbContext<ApplicationUser>, does that mean I should have seperate database contexts for my user authentication stuff provided by Visual Studio, and my own code?

I think my end goal is to use my own database context, called DatabaseContext, which is then used in a base controller that all of my controllers inherit from. Then I only have one place where the database context is instantiated, instead of within every controller.

Who knows, I may be thinking the wrong way about this. Everybody seems to have their own preferred way of dealing with this.

Thank you!

1
7
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?

  • If you decided that you are going to have access to DB directly from UI layer (Which is a separate discussion) than it is OK, since ApplicationDbContext is a private field of your controller and controllers are created and disposed per request - ApplicationDbContext will be created and disposed per request.

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

  • You definitely can do it. It is used to create a UserStore which receives DbContext as an argument in constructor so this

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

will work. You still have to make sure that ApplicationUser is an entity in your custom context. Of course you can override/replace ApplicationUser as well.

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?

By default Asp.Net Identity generates a new data base for you and ApplicationDbContext configured to work with this data base. You can store your authentication related entities in any other data base as well, you just need to make sure that all the related tables are there.You can also extend this data base to include other tables that you are using in your application so you could use the same context all over.

P.S: ApplicationDbContext doesn't have to implement IdentityDbContext<ApplicationUser>, Extending a default DbContext works as well (if you already generated a Db you will have to update it\use code migrations for the following to work):

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

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

Popular Answer

I think you would like to create your own custom authentication database for login authentication. You need to follow the given instructions step by step. 1) you need to create your own class to implement custom authentication. for example, I am creating following student class .You can create this class in MODEL section in MVC.

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

2)now you going to create Your own dbcontext using identityDbContext for student class. you can create this class in App_Start section like this.

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

        }

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

3) now you can use it home in controller as follow

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,
                HttpContext.GetOwinContext().Authentication);
            var username  = "Edward";
            var email = "abc@gmail.com";
            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 members.so 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);
            }
            else
            {
                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





Related

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