前提:
- 在没有程序员进行指导的情况下,实施可以快速进行项目部署;
- 无需执行数据库脚本,程序员告别繁琐的数据库建表操作,以及默认数据的配置;
Step1:项目引用添加 Microsoft.EntityFrameworkCore
Step2:
在Startup.cs文件中的ConfigureServices方法内添加代码
services.AddDbContext<CoreDbContext>(options => options.UseSqlServer("你的数据库链接字符串"));
Step3:
新建文件DbContextSeed.cs
using Microsoft.EntityFrameworkCore; using RunGo.Core.Expand; using RunGo.Core.Managing; using System; using System.Linq; using System.Threading.Tasks; using UtilHelp; namespace RunGo.Core.Web.Host.Startup.Initialize { namespace mvcforcookie.Data { public class DbContextSeed { private string badStr = "初始化数据库失败"; private string okStr = "初始化数据库成功"; public async Task SeedAsync(DbContext context, IServiceProvider service) { if (context.Set<Tenants>().Count() == 0) { //创建初始租户 var defultTenant = new Tenants() { Name = DefaultSet.DefaultName, TenancyName = DefaultSet.DefaultCName, PassWord = EncryptionHelp.MD5Encrypt64("123456", DefaultSet.DefaultName), Id = DefaultSet.DefaultId }; try { await context.AddAsync(defultTenant); var result = await context.SaveChangesAsync(); if (result == 0) Console.WriteLine(badStr); else Console.WriteLine(okStr); } catch (Exception e) { Console.WriteLine(badStr); } } } } } }
新建文件 InitializeTheDBExtensions.cs
using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using System; namespace RunGo.Core.Web.Host.Startup.Initialize { public static class InitializeTheDBExtensions { /// <summary> /// 初始化数据库 /// </summary> /// <param name="host"></param> /// <param name="sedder"></param> /// <returns></returns> public static IWebHost InitializeDbContext<TContext>(this IWebHost host, Action<TContext, IServiceProvider> sedder) where TContext : DbContext { using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; var context = services.GetService<TContext>(); try { context.Database.Migrate(); sedder(context, services); } catch (Exception ex) { Console.WriteLine("初始化失败"); } } return host; } } }
Step4:在Main方法里调用初始化方法
public static void Main(string[] args) { BuildWebHost(args) .InitializeDbContext<CoreDbContext>((context, services) => { new DbContextSeed().SeedAsync(context, services).Wait(); }) .Run(); }
Step5:执行项目即可看到成果了。