在本章中,我们将讨论Identity迁移。 在ASP.NET Core MVC中,在Startup.cs文件中配置了身份验证和身份功能。
1 2 3 4 5 6 7 8 9 10 public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddEntityFramework() .AddSqlServer() .AddDbContext<FirstAppDemoDbContext>option. UseSqlServer(Configuration[ "database:connection" ])); services.AddIdentity<User, IdentityRole>() .AddEntityFrameworkStores<FirstAppDemoDbContext>(); }无论何时对一个实体类进行更改或对DBContext派生类进行更改,您都必须创建一个新的迁移脚本以应用于数据库,并使模式与您的代码同步 。
这是我们的应用程序中的情况,因为我们现在从IdentityDbContext类中派生出FirstAppDemoDbContext类,并且它包含自己的DbSets,它还将创建一个模式来存储有关它管理的实体的所有信息。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.Data.Entity; namespace FirstAppDemo.Models { public class FirstAppDemoDbContext : IdentityDbContext<User> { public DbSet<Employee> Employees { get ; set ; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer("Data Source = (localdb)\\MSSQLLocalDB; Initial Catalog = FirstAppDemo;Integrated Security = True; Connect Timeout = 30;Encrypt = False; TrustServerCertificate = True;ApplicationIntent = ReadWrite; MultiSubnetFailover = False"); } } }让我们现在打开命令提示符,并确保我们在我们的项目的project.json文件存在的位置。
我们还可以通过键入dnx ef获得Entity Framework命令。
我们的project.json文件有一个将“ef”关键字与EntityFramework.Commands映射的部分。
1 2 3 4 "commands" : { "web" : "Microsoft.AspNet.Server.Kestrel" , "ef" : "EntityFramework.Commands" }我们可以从这里添加迁移。 我们还需要为迁移提供一个名称。 让我们使用v2作为第二个版本的名称,然后按enter键。
迁移完成后,您将在migrations文件夹中有一个v2文件。
我们现在要通过运行“dnx ef database update”命令将该迁移应用到我们的数据库。
实体框架将看到有一个需要应用的迁移,它将执行该迁移。
如果进入SQL Server对象资源管理器,您将看到我们之前创建的Employee表。 您还将看到一些额外的表,这些表必须存储用户,声明,角色和将用户映射到特定角色的一些映射表。
所有这些表都与Identity框架提供的实体相关。
让我们快速查看users表。
您现在可以看到AspNetUsers表中的列,用于存储我们从我们继承的Identity User中看到的所有属性,以及其字段(如UserName和PasswordHash)。 因此,您已经使用了一些内置的身份服务,因为它们还包含创建用户并验证用户密码的能力。
版权声明:本站所有教程均为本站原创或翻译,转载请注明出处,请尊重他人劳动果实。请记住本站地址:www.yuanjiaocheng.net (猿教程) 作者:卿文刚 本文标题: Asp.Net Core-Identity迁移 本文地址:http://www.yuanjiaocheng.net/ASPNET-CORE/core-identity-migrations.html