1. 使用DbContextSeed初始化数据库
    1. 添加链接字符串

       // This method gets called by the runtime. Use this method to add services to the container.
      public void ConfigureServices(IServiceCollection services)
      {
      //添加链接字符串
      services.AddDbContext<ApplicationDbContext>(options =>
      options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddMvc();
      }
    2. 添加初始化数据类和方法
      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Threading.Tasks; namespace mvcforcookie.Data
      {
      using Models;
      using Microsoft.AspNetCore.Identity;
      using Microsoft.Extensions.DependencyInjection;//CreateScope()
      public class ApplicationDbContextSeed
      {
      private UserManager<ApplicationUser> _userManager;
      public async Task SeedAsync(ApplicationDbContext context, IServiceProvider service)
      {
      if (!context.Users.Any())
      {
      _userManager = service.GetRequiredService<UserManager<ApplicationUser>>();
      //创建初始用户
      var defultUser = new ApplicationUser()
      {
      UserName = "Administrator",
      Email = "453151742@qq.com",
      NormalizedUserName = "admin"
      };
      var result = await _userManager.CreateAsync(defultUser, "Password$123");
      if (!result.Succeeded)
      {
      throw new Exception("初始用户创建失败");
      }
      }
      }
      }
      }
      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Threading.Tasks; namespace mvcforcookie.Data
      {
      using Microsoft.AspNetCore.Hosting;
      using Microsoft.EntityFrameworkCore;
      using Microsoft.Extensions.DependencyInjection;
      using Microsoft.Extensions.Logging;
      public static class WebHostMigrationExtensions
      {
      /// <summary>
      /// 初始化database方法
      /// </summary>
      /// <typeparam name="TContext"></typeparam>
      /// <param name="host"></param>
      /// <param name="sedder"></param>
      /// <returns></returns>
      public static IWebHost MigrateDbContext<TContext>(this IWebHost host, Action<TContext, IServiceProvider> sedder)
      where TContext : ApplicationDbContext
      {
      //创建数据库实例在本区域有效
      using (var scope=host.Services.CreateScope())
      {
      var services = scope.ServiceProvider;
      var logger = services.GetRequiredService<ILogger<TContext>>();
      var context = services.GetService<TContext>();
      try
      {
      context.Database.Migrate();//初始化database
      sedder(context, services);
      logger.LogInformation($"执行DbContext{typeof(TContext).Name} seed 成功");
      }
      catch ( Exception ex)
      {
      logger.LogError(ex, $"执行dbcontext {typeof(TContext).Name} seed失败");
      }
      }
      return host;
      }
      }
      }
    3. BuildWebHost时注入初始化函数

      using System;
      using System.Collections.Generic;
      using System.IO;
      using System.Linq;
      using System.Threading.Tasks;
      using Microsoft.AspNetCore;
      using Microsoft.AspNetCore.Hosting;
      using Microsoft.Extensions.Configuration;
      using Microsoft.Extensions.Logging; namespace mvcforcookie
      {
      using mvcforcookie.Data;
      public class Program
      {
      public static void Main(string[] args)
      {
      BuildWebHost(args)
      .MigrateDbContext<ApplicationDbContext>((context, services) =>
      { new ApplicationDbContextSeed().SeedAsync(context, services).Wait(); })
      .Run();
      } public static IWebHost BuildWebHost(string[] args) =>
      WebHost.CreateDefaultBuilder(args)
      .UseStartup<Startup>()
      .Build();
      }
      }

  

  1. 使用services注入初始化数据库
    1. 添加Nuget包IdentityServer4.EntityFramework
    2. 添加链接字符串初始化dbcontext
       public void ConfigureServices(IServiceCollection services)
      {
      var connectionstr = "Server=(localdb)\\mssqllocaldb;Database=IdentityServer4.EntityFramework;Trusted_Connection=True;MultipleActiveResultSets=true";
      var migrationAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
      // //添加identity
      services.AddIdentity<ApplicationUser, ApplicationUserRole>()
      .AddEntityFrameworkStores<ApplicationDbContext>()
      .AddDefaultTokenProviders(); services.AddIdentityServer()
      .AddDeveloperSigningCredential()//添加证书
      .AddConfigurationStore(options=> {//添加ConfigurationStore的配置存储claims
      options.ConfigureDbContext = builder =>
      {
      builder.UseSqlServer(connectionstr, sql => sql.MigrationsAssembly(migrationAssembly));
      };
      })
      .AddOperationalStore(options => {//添加OperationalStore的配置存储token的表格控制
      options.ConfigureDbContext = builder =>
      {
      builder.UseSqlServer(connectionstr, sql => sql.MigrationsAssembly(migrationAssembly));
      };
      })
      .AddAspNetIdentity<ApplicationUser>()//添加identityuser
      .Services.AddScoped<IProfileService,ProfileService>();//添加profileservice
      services.AddMvc();
      }
    3. 使用命令行初始化数据库
      Add-Migration InitConfigurations -Context ConfigurationDbContext -OutputDir Data\Migrations\IdentityServer\Configuration
      
      Add-Migration InitPersistedGrant -Context PersistedGrantDbContext -OutputDir Data\Migrations\IdentityServer\PersistedGrantDb
      
       DBcontext 在 Identityserver4.EntityFramwork.DbContexts 命名空间下
      
      Update-Database -Context ConfigurationDbContext 
      
      Update-Database -Context PersistedGrantDbContext
    4. 添加初始化数据的方法
      using System.Collections.Generic;
      using System.Collections;
      using IdentityServer4.Models;
      using IdentityServer4.Test;
      using IdentityServer4;
      using System.Security.Claims; namespace mvcforcookie
      {
      public class Config
      {
      public static IEnumerable<ApiResource> GetApiResoure()
      {
      return new List<ApiResource>() { new ApiResource("api1", "My Api") };
      }
      public static IEnumerable<IdentityServer4.Models.Client> GetClients()
      {
      return new List<IdentityServer4.Models.Client>()
      {
      //正常情况下配置在数据库当中
      new IdentityServer4.Models.Client() {
      ClientId="MVC",
      ClientName="MVC",
      ClientUri="http://localhost:5001",
      LogoUri="https://www.nicepsd.com/image/ec3594cb9bd94e13a7078b5da254591e/image.jpg",
      AllowRememberConsent=true,//是否可以记住
      //AllowedGrantTypes =GrantTypes.Implicit,//隐式 模式
      AllowedGrantTypes =GrantTypes.HybridAndClientCredentials,
      RequireConsent=true,//用户是否要确认
      ClientSecrets={new Secret("Secret".Sha256())},//密鑰
      AllowAccessTokensViaBrowser=true,
      AllowOfflineAccess=true,
      RedirectUris={ "http://localhost:5001/signin-oidc"},//客户端 登陆的url
      PostLogoutRedirectUris={ "http://localhost:5001/signout-callback-oidc"},//登出地址
      AlwaysIncludeUserClaimsInIdToken=true,//IdToken是否携带claims返回到客户端
      AllowedScopes={
      //使用identity4
      IdentityServerConstants.StandardScopes.Profile,
      IdentityServerConstants.StandardScopes.OpenId,
      IdentityServerConstants.StandardScopes.Profile
      }
      }
      };
      } public static List<TestUser> GetTestuser()
      {
      return new List<TestUser>(){new TestUser(){
      SubjectId="",
      Username ="cyao",
      Password="oauth",
      Claims =new List<Claim>{
      new Claim("name","cyao"),
      new Claim("webSite","www.baidu.com")
      }
      }};
      } public static IEnumerable<IdentityResource> GetIdentityResource()
      {
      return new List<IdentityResource>(){
      new IdentityResources.OpenId(),
      new IdentityResources.Profile()
      }; }
      }
      }
    5. 执行Init方法

          // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
      public void Configure(IApplicationBuilder app, IHostingEnvironment env)
      {
      if (env.IsDevelopment())
      {
      app.UseDeveloperExceptionPage();
      }
      else
      {
      app.UseExceptionHandler("/Home/Error");
      }
      //一定要先执行数据库生成命令然后执行初始化数据库
      InitIdentityServerDataBase(app);//初始化数据库
      app.UseStaticFiles();
      // app.UseAuthentication();
      app.UseIdentityServer();
      app.UseMvc(routes =>
      {
      routes.MapRoute(
      name: "default",
      template: "{controller=Home}/{action=Index}/{id?}");
      });
      }
      /// <summary>
      /// 初始化数据库
      /// </summary>
      /// <param name="app"></param>
      public void InitIdentityServerDataBase(IApplicationBuilder app) {
      using (var scope=app.ApplicationServices.CreateScope()) {
      scope.ServiceProvider.GetRequiredService<PersistedGrantDbContext>().Database.Migrate();
      var configurationDbContext = scope.ServiceProvider.GetRequiredService<ConfigurationDbContext>();
      if (!configurationDbContext.Clients.Any())
      {
      foreach (var client in Config.GetClients())
      {
      configurationDbContext.Clients.Add(client.ToEntity());
      }
      configurationDbContext.SaveChanges();
      }
      if (!configurationDbContext.ApiResources.Any())
      {
      foreach (var api in Config.GetApiResoure())
      {
      configurationDbContext.ApiResources.Add(api.ToEntity());
      }
      configurationDbContext.SaveChanges();
      }
      if (!configurationDbContext.IdentityResources.Any())
      {
      foreach (var identity in Config.GetIdentityResource())
      {
      configurationDbContext.IdentityResources.Add(identity.ToEntity());
      }
      configurationDbContext.SaveChanges();
      }
      }
      }

EF Core 初始化数据库的两种方法。的更多相关文章

  1. C++连接mysql数据库的两种方法

    本文主要介绍了C++连接mysql数据库的两种方法,希望通过本文,能对你有所帮助,一起来看. 现在正做一个接口,通过不同的连接字符串操作不同的数据库.要用到mysql数据库,以前没用过这个数据库,用a ...

  2. python学习--python 连接SQLServer数据库(两种方法)

    1. python 学习.安装教程参照: http://www.runoob.com/python/python-tutorial.html 2. 集成开发环境 JetBrains PyCharm C ...

  3. python更新数据库脚本两种方法

    最近项目的两次版本迭代中,根据业务需求的变化,需要对数据库进行更新,两次分别使用了不同的方式进行更新. 第一种:使用python的MySQLdb模块利用原生的sql语句进行更新 import MySQ ...

  4. 【Python】python更新数据库脚本两种方法

    最近项目的两次版本迭代中,根据业务需求的变化,需要对数据库进行更新,两次分别使用了不同的方式进行更新. 第一种:使用python的MySQLdb模块利用原生的sql语句进行更新   1 import ...

  5. c#取数据库数据 ---两种方法

    通常有以下两种方式 SqlDataReader 和SqlDataAdapter|DataSet方式 SqlDataReader 方式使用方式如下: using System; using System ...

  6. DataGridView编辑后立即更新到数据库的两种方法

    DataGridView控件是微软预先写好的一个显示数据的控件,功能非常强大,可以显示来自数据库表的数据和XML等其他来源的数据. 方法一:基于DataAdapter对象创建一个CommandBuli ...

  7. iOS UIimage初始化时的两种方法

    第一种方式:UIImage *image = [UIImage imageNamed:@"image"]; 使用这种方式,第一次读取的时候,先把这个图片存到缓存里,下次再使用时直接 ...

  8. MySQL 创建数据库的两种方法

    使用 mysqladmin 创建数据库 使用普通用户,你可能需要特定的权限来创建或者删除 MySQL 数据库. 所以我们这边使用root用户登录,root用户拥有最高权限,可以使用 mysql mys ...

  9. c#访问数据库的两种方法以及事务的两种方法

    //2015/07/03 using System; using System.Collections.Generic; using System.Linq; using System.Text; u ...

随机推荐

  1. bootstrap-table(2)问题集

    参考;https://www.cnblogs.com/landeanfen/p/4993979.html 1.分页参数sidePagination 如果是服务端分页,返回的结果必须包含total.ro ...

  2. squid之------安装与基本配置

    1.rpm安装squid yum -y install squid 2.squid主要组成部分 服务名:squid 主程序:/usr/sbin/squid 配置目录:/etc/squid 主配置文件: ...

  3. jquery header选择器 语法

    jquery header选择器 语法 作用::header 选择器选取所有标题元素(h1 - h6).广州大理石机械构件 语法:$(":header") jquery heade ...

  4. 与HTTP协作的Web服务器——代理、网关、隧道

    1.虚拟主机 (1)HTTP/1.1规范允许一台HTTP服务器搭建多个Web站点: (2)在互联网上,域名通过DNS服务映射到IP地址(域名解析)之后访问目标网站,即当请求发送到服务器时,已经是以IP ...

  5. Qt新建工程

    1.基本步骤 (1)Qt Quick Project是开发QML语言的: (2)Qt Widget Project是基于部件的开发,一种是PC的Qt Gui Application,一种是手机的Mob ...

  6. [luogu]P1514 引水入城[搜索][记忆化][DP]

    [luogu]P1514 引水入城 引水入城 题目描述在一个遥远的国度,一侧是风景秀美的湖泊,另一侧则是漫无边际的沙漠.该国的行政区划十分特殊,刚好构成一个N 行M 列的矩形 ,如下图所示,其中每个格 ...

  7. SpringBoot2.2发行版新特性

    Spring Framework升级 SpringBoot2.2的底层Spring Framework版本升级为5.2. JMX默认禁用 默认情况下不再启用JMX. 可以使用配置属性spring.jm ...

  8. DVWA--XSS(stored)

    XSS 0X01 1.简介 跨站脚本(cross site script)为了避免与样式css混淆,所以简称为XSS. XSS是一种经常出现在web应用中的计算机安全漏洞,也是web中最主流的攻击方式 ...

  9. [BZOJ3990]:[SDOI2015]排序(搜索)

    题目传送门 题目描述 小A有一个1-${2}^{N}$的排列A[1..${2}^{N}$],他希望将A数组从小到大排序,小A可以执行的操作有N种,每种操作最多可以执行一次,对于所有的i(1≤i≤N), ...

  10. 大数据笔记(二十七)——Spark Core简介及安装配置

    1.Spark Core: 类似MapReduce 核心:RDD 2.Spark SQL: 类似Hive,支持SQL 3.Spark Streaming:类似Storm =============== ...