ASP.NET Identity 3.0 - 如何在 MVC 应用程序中创建带有用户表的数据库?

ASP.NET Identity 3.0 - how is the database with user tables created in an MVC application?

我正在尝试从头开始构建一个简单的登录系统,使用 ASP.NET MVC v5、Entity Framework v7 和 Identity v3 的代码优先方法。我正在根据 ASP.NET MVC 应用程序和 Visual Studio 附带的个人用户登录模板对我的应用程序进行建模。

我只想让用户创建一个帐户,并将该帐户保存在数据库中。

这是我目前的代码:

Startup.cs:

public class Startup
{
    public IConfigurationRoot Configuration { get; set; }
    public Startup()
    {
        var builder = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json");
        builder.AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddEntityFramework()
            .AddSqlServer()
            .AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));

        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        services.AddMvc();
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear());
        app.UseStaticFiles();
        app.UseIdentity();
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }

    public static void Main(string[] args) => WebApplication.Run<Startup>(args);
}

appsettings.json 包含连接数据库的代码:

"Data": {
  "DefaultConnection": {
    "ConnectionString": "Server=(localdb)\mssqllocaldb;Database=SimpleAuthenticationApp;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}

这是 Controllers/AccountController.cs 中注册 POST 操作的代码:

    [HttpPost]
    public async Task<IActionResult> Register (RegisterViewModel model)
    {
        try
        {
            var user = new ApplicationUser { UserName = model.Email };
            IdentityResult result = await _userManager.CreateAsync(user, model.Password);
            Console.WriteLine(result);
            return View("Home", "Index");
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
            return View();
        }
    }

在此代码中,RegisterViewModel 只是一个包含电子邮件、密码和确认密码字段的 ViewModel。 Account/Register 视图只是一个要求这些字段的表单。 ApplicationUser 是从 IdentityUser.

延伸而来的 class

在POST路由中,我在try块设置了一个断点,进入catch块时,异常显示为"Invalid object name AspNetUsers."

在我在此应用程序中创建第一个用户之前,没有数据库。我注册了一个新用户,该应用程序将我带到一个错误页面阅读,"Applying existing migrations for ApplicationDbContext may resolve this issue" 带有一个应用迁移的按钮。当我点击按钮时,数据库就创建好了。我注意到当我 运行 默认 MVC with Users 应用程序时,有一个 Migrations 文件夹包含 00000000000000_CreateIdentitySchema.csApplicationDbContextModelSnapshot.cs 看起来它们包含创建具有所需表的数据库的设置。我尝试在我的应用程序中使用这些文件,但没有任何区别。

我的问题:

EntityFramework 使用持续迁移概念在需要时升级您的数据库模式。默认情况下,初始迁移会创建您已经发现的 user/identity 表。您不必直接对 Migrations 文件夹中的代码执行任何操作;如果您设置迁移初始化程序,则数据库在启动时可以是 initialised/upgraded:

我建议通读本演练,以更好地了解正在发生的事情以及您可以用它做什么:

https://msdn.microsoft.com/en-us/data/jj591621.aspx

我上面提到的 auto-initialisation/upgrade 场景在本文中有所介绍。

老实说,我不得不在这里写一篇关于这个的长篇文章:https://medium.com/@goodealsnow/asp-net-core-identity-3-0-6018fc151b4 通常,您可以使用 dotnet cli 来部署迁移 dotnet ef 迁移添加 Version2CoolWaves -o Data\Migrations

但请阅读我的完整文章以获取分步教程。