新的 ASP.NET MVC 5 应用程序如何知道如何创建数据库以及帐户控制器如何访问数据库? [英] How does a new ASP.NET MVC 5 application know how to create a database and how does the Account Controller access the database?

查看:17
本文介绍了新的 ASP.NET MVC 5 应用程序如何知道如何创建数据库以及帐户控制器如何访问数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Visual Studio 2013 Update 2 创建了一个 ASP.NET MVC 5 应用程序.在应用程序中,我有一个帐户控制器.它与我习惯的不同包含 dbcontext 的实例化.

I created an ASP.NET MVC 5 Application using Visual Studio 2013 Update 2. In the application, I have an Account controller. It's different from what I am used to and does not contain an instantiation 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;
        }
    }

默认创建的我的 web.config 有一个像这样的连接字符串:

My web.config that is created by default has a connection string 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 explain to me how the application knows to create a database for this application when it starts for the first time?

此外,在后续启动时,它是否使用实体框架访问身份表来进行身份验证?

Also, on subsequent starts, does it use Entity Framework to access the Identity tables to do the authentication?

推荐答案

1) 这里发生了什么:

当您创建一个新的 MVC 5 应用程序并选择个人用户帐户"时,一个新的 ASP.NET Identity Provider 包含在内,它使用 Entity Framework 6 Code-First.

When you create a new MVC 5 application and choose "Individual User Accounts", a new ASP.NET Identity Provider is included which uses Entity Framework 6 Code-First.

Microsoft 已采用 EF-Code-First 使 Identity 尽可能可定制.

Microsoft has adopted EF-Code-First to make Identity as customizable as possible.

当第一次访问 Identity 时,实体框架会检查数据库是否存在.除非另外配置,否则它使用 "DefaultConnection" 来查找身份数据库.如果调用 Identity 时数据库不存在,EF 会自动创建数据库.

When Identity is accessed for the first time, Entity Framework checks to see if the database exists. Unless configured otherwise, it uses the "DefaultConnection" to find the identity database. If the database does not exist when Identity is called, EF automatically created the database.

注意你的连接字符串包含

Notice your connection string contains

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

如果您打开 App_Data 文件夹,您应该有一个 aspnet-WebApplication3-20140417072624.mdf 文件.

如果您双击这个 .mdf 文件,VS2013 Server Explorer 将打开您的数据库.如果您已经尝试访问任何身份功能,您将创建这些表:

If you double click on this .mdf file, the VS2013 Server Explorer will open your DB. If you have already attempted to access any Identity functionality, you will these tables created:

  • _MigrationHistory
  • ASPNetRoles
  • ASPNetUserClaims
  • ASPNetUserLogins
  • ASPNetUsers

默认情况下,您的应用配置为使用 SQL Server Compact(MDF 文件),因此您不必拥有实际的 SQL服务器 实例正在运行.所有这些都是可定制的.MDF 文件的名称、身份数据库的架构、SQL Compact 与实际 SQL Server 的选择> 实例.更改您的连接字符串,或创建一个新连接并将此新连接传递给您的上下文.

By default, your app is configured to use SQL Server Compact (MDF file) so you don't have to have an actual SQL Server Instance running. All of this is customizable. The name of your MDF file, the schema of Identity Database, the choice of SQL Compact vs an actual SQL Server instance. Change your Connection String, or create a new one and pass this new connection to your context.

2) 我的上下文在哪里?

所有这些都很好,但您提出的一个重要问题基本上是我的上下文在哪里?",以及关于如何进一步自定义您的数据库或更改的相关隐含问题验证逻辑.

All this is well and good, but an important question you asked is basically "Where is my context?", and the just as relevant implied questions regarding how you can further customize your DB or alter validation logic.

您会注意到您的项目引用了 Microsoft.AspNet.Identity.EntityFramework.该程序集是 IdentityDBContext 的实现和 UserManager 类的实现.

You will notice that your project references Microsoft.AspNet.Identity.EntityFramework. This assembly is an implementation of IdentityDBContext<TUser> and implentation of UserManager Class.

打开您的 AccountController,注意构造函数传递了 UserManager 对象,该对象又传递了一个 new UserStore传递的对象,它传递了一个 ApplicationDbContext.

Open your AccountController, and notice the constructor has UserManager object passed which in turn has a new UserStore object passed, which gets passed a ApplicationDbContext.

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

ApplicationDbContext 在您的 Models 文件夹中定义.在该文件夹中,您会找到一个 IdentityModels.cs 文件.打开它,你会看到

The ApplicationDbContext is defined in your Models Folder. Inside that folder, you will find an IdentityModels.cs file. Open it and you will see

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

这是分配您的身份上下文的地方.您可以更改传递给 ApplicationDbContext 构造函数的连接名称,或者在您的帐户控制器中定义和使用不同的上下文.

This is where your Identity Context is assigned. you can change the connection name passed to the ApplicationDbContext constructor, or define and use a different context in your account controller.

3) 我如何自定义我的身份架构?

IdentityModels.cs 文件中定义的另一个类是从 IdentityUser 类继承的 ApplicationUser 类.

Another class defined IN IdentityModels.cs file is the ApplicationUser class which inherits from IdentityUser class.

public class ApplicationUser : IdentityUser
{
}

您添加到此类的任何属性都将保留在您的ASPNetUsers 表中.架构的其余部分在 IdentityDbContext 类中定义.因此,虽然您可以通过向上下文定义添加 DBSet 来向身份架构添加更多表(例如权限),

Any properties you add to this class will be persisted in your ASPNetUsers Table. The rest of the schema is defined in IdentityDbContext class. So, while you can add more tables (e.g. Privileges) to your Identity Schema by adding a DBSet to the Context Definition,

public DBSet<Privileges> { get; set; }

也可以更改其他表(角色、声明等),但涉及的范围要大得多.例如,要自定义 Roles 表,您必须实现从 IdentityRole 继承的 NewIdentityRole 并通过覆盖 添加它的关系上下文的 OnModelCreating() 方法.

Altering other tables (Roles, Claims, etc) is also possible, but far more involved. For example, to customize the Roles table, you would have to implement a NewIdentityRole inheriting from IdentityRole and add it's relationship by overriding the OnModelCreating() method for your Context.

这篇关于自定义的文章角色表 很好地描述了所涉及的步骤.即使在这里,您也会发现简单地添加新列会带来很大的麻烦.从 IdentityDbContext 类中创建的原始模式中删除表或列可能与创建自己的 IdentityDbContext 类实现一样麻烦.

This article on Customizing Roles Tables does a good job of describing the steps involved. Even here, you will find that there is significant trouble invested into simply ADDING new columns. Removing tables or columns from the original schema created in the IdentityDbContext class is probably as much trouble as creating your own implementation of IdentityDbContext class.

这篇关于新的 ASP.NET MVC 5 应用程序如何知道如何创建数据库以及帐户控制器如何访问数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆