• 【ASP.NET Core快速入门】(十六)MVC开发:DbContextSeed初始化


    前言

    由于我们现在每次EF实体模型变化的时候每次都是手动更改,我们想通过代码的方式让他自动更新,或者程序启动的时候添加一些数据进去

    DbContextSeed初始化

    首先,在Data文件夹下添加一个ApplicationDbContextSeed.cs初始化类

    using Microsoft.AspNetCore.Identity;
    using MvcCookieAuthSample.Models;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.Extensions.DependencyInjection;
    
    namespace MvcCookieAuthSample.Data
    {
        public class ApplicationDbContextSeed
        {
            private UserManager<ApplicationUser> _userManager;
    
            public async Task SeedAsync(ApplicationDbContext context, IServiceProvider services)
            {
                if (!context.Users.Any())
                {
                    _userManager = services.GetRequiredService<UserManager<ApplicationUser>>();
    
                    var defaultUser = new ApplicationUser
                    {
                         UserName="Administrator",
                         Email="786744873@qq.com",
                         NormalizedUserName="admin"
                    };
    
                    var result= await _userManager.CreateAsync(defaultUser,"Password$123");
                    if (!result.Succeeded)
                    {
                        throw new Exception("初始默认用户失败");
                    }
                }
            }
        }
    }

    那么如何调用呢?接下来我们写一个WebHost的扩展方法类WebHostMigrationExtensions.cs来调用ApplicationDbContextSeed方法

    using Microsoft.AspNetCore.Hosting;
    using Microsoft.EntityFrameworkCore;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Logging;
    
    namespace MvcCookieAuthSample.Data
    {
        public static class WebHostMigrationExtensions
        {
            public static IWebHost MigrateDbContext<TContext>(this IWebHost host, Action<TContext, IServiceProvider> sedder) where TContext : DbContext
            {
                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();
                        sedder(context, services);
    
                        logger.LogInformation($"执行DBContext {typeof(TContext).Name} seed执行成功");
                    }
                    catch (Exception ex)
                    {
                        logger.LogError(ex, $"执行DBContext {typeof(TContext).Name} seed方法失败");
                    }
                }
    
                return host;
            }
        }
    }

    那么我们程序启动的时候要怎调用呢?

    要在Program.cs中执行

     我们接下来把数据库删掉,然后启动程序运行一下

    数据库已自动生成并插入数据

    源码点击下载

    Core2.2版本源码

  • 相关阅读:
    英特尔“硬盘内存一体化”首款产品正式发布,读写速度超千倍,存储密度扩充十倍
    程序员,你为什么值这么多钱?
    不懂程序看的明白《黑客帝国》吗?
    程序员的工作、学习与绩效
    架构设计师能力模型
    .net平台的MongoDB使用
    转载-30分钟搞定后台登录界面(103个后台PSD源文件、素材网站)
    XAF-DevExpress.ExpressApp.DC.Xpo.XpoTypeInfoSource 生成实体的过程-学习笔记
    谈谈敏捷开发
    XAF-由于try catch导致的性能问题一例
  • 原文地址:https://www.cnblogs.com/wyt007/p/8253164.html
Copyright © 2020-2023  润新知