How does a new ASP.NET MVC 5 application know how to create a database and how does the Account Controller access the database?

asp.net asp.net-identity asp.net-mvc asp.net-mvc-5 entity-framework

Question

I used Update 2 for Visual Studio 2013 to construct a MVC 5 for ASP.NET application. I have a controller of accounts in the program. It differs from my experience and does not include an instance of dbcontext.

public class AccountController : Controller
{
    private ApplicationUserManager _userManager;

    public AccountController()
    {
    }

    public AccountController(ApplicationUserManager userManager)
    {
        UserManager = userManager;
    }

    public ApplicationUserManager UserManager {
        get
        {
            return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
        }
        private set
        {
            _userManager = value;
        }
    }

My web.config has a connection string that looks something like this:

  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-WebApplication3-20140417072624.mdf;Initial Catalog=aspnet-WebApplication3-20140417072624;Integrated Security=True"
      providerName="System.Data.SqlClient" />
  </connectionStrings>

Can someone please explain how the program learns to set up a database when it starts up for the first time?

Does it use Entity Framework to access the Identity tables for authentication on subsequent starts as well?

1
34
5/17/2015 7:43:22 PM

Accepted Answer

1) What is happening here:

A new Identity Provider for ASP.NET that utilizes Framework Entity 6 Code-First is added when you build a new MVC 5 application and select "Users' individual accounts."

In order to make Identity as adaptable as feasible, Microsoft adopted EF-Code-First.

The first time Identity is accessed, Enterprise Framework verifies that the database is present. Unless otherwise specified, it uses the"DefaultConnection" the identity database can be located. When Identity is called, EF will automatically construct the database if it doesn't already exist.

Note the following in your connection string:

`AttachDbFilename=|DataDirectory|\aspnet-WebApplication3-20140417072624.mdf`

There should be a aspnet-WebApplication3-20140417072624.mdf file in your App_Data Folder when you open it.

This .mdf file will open your DB when you double click it. These tables will have been generated if you have already attempted to access any Identity functionality:

  • _MigrationHistory
  • ASPNetRoles
  • ASPNetUserClaims
  • ASPNetUserLogins
  • ASPNetUsers

You don't need to have a real Server SQL instance running because your app is set up by default to use Compact SQL Server (MDF file). Everything here is changeable. The name of your MDF file, the Identity Database structure, and your decision to use Compact SQL as opposed to a real Server SQL instance. Alternately, make a new Connection String and provide it to your context along with your existing one.


Where is my context, please?

All of this is fine and excellent, but you essentially asked "What about my context?" and the equally pertinent implication questions of how you may further customize your DB or change validation logic.

You'll see that the references in your projectMicrosoft.AspNet.Identity.EntityFramework This assembly is a practical application ofIdentityDBContext<TUser> and the implementationUserManager Class.

When you open your AccountController, you'll see that the builder hasUserManager passed object, which in turn has anew UserStore passed object that receives aApplicationDbContext .

    public AccountController()
        : this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))

The ApplicationDbContext is specified in your folder, Models. You can locate a IdentityModels.cs file in that folder. You can see if you open it.

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

Your Identity Context is assigned here. The connection name provided to the server can be changed.ApplicationDbContext either define and use a new context in your account controller instead of the constructor.


How can I customize my identity scheme?

The class described in the IdentityModels.cs file is another one.ApplicationUser class that derives fromIdentityUser class.

public class ApplicationUser : IdentityUser
{
}

Anything you add to this class in terms of properties will be stored in your ASPNetUsers Table. Describes the remainder of the schemaIdentityDbContext class. As a result, while adding a DBSet to the Context Definition would allow you to add extra tables to your Identity Schema, such as Privileges,

public DBSet<Privileges> { get; set; }

Roles, Claims, and other tables can also be changed, although doing so is much more difficult. For instance, if you wanted to alter the Roles table, you would have to putNewIdentityRole obtaining fromIdentityRole and further its connection by overriding theOnModelCreating() for your Context, please.

The steps are well-explained in this article on Creating a Custom Roles Table. Even here, you will discover that adding extra columns involves a great deal of effort. deleting columns or tables from the initial schema developed in theIdentityDbContext It's probably just as difficult to implement a class as it is toIdentityDbContext class.

78
4/19/2014 10:37:58 PM

Popular Answer

Melina correctly noted that the initial query made mention of the existing ASP.NET Identity 2.x paradigm.

Although the examples were taken from ASP.NET Identity 1.x, which was replaced in 2014, Dave Alperovich's response included useful context for the ideas underpinning ASP.NET Identity.

The advice to "teach a man to fish" is given by Callum Linington. It is simple to see that the 2.x "ApplicationUserManager" class is descended from a 1.x-style "UserManager" by taking his instructions.

The "ApplicationUserManager," which is injected as a parameter when "AccountController" is constructed, basically connects to the identity data store in its own constructor, which is the main explanation:

var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));

Take note of how closely this "secret" 2.x code resembles the 1.x code previously provided:

public AccountController()
    : this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))


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