基于 abp vNext 和 .NET Core 开发博客项目 - 数据访问和代码优先 (3)

1

代码优先

在.EntityFrameworkCore.DbMigrations中新建模块类MeowvBlogEntityFrameworkCoreDbMigrationsModule.cs、数据迁移上下文访问对象MeowvBlogMigrationsDbContext.cs和一个Design Time Db Factory类MeowvBlogMigrationsDbContextFactory.cs

模块类依赖MeowvBlogFrameworkCoreModule模块和AbpModule。并在ConfigureServices方法中添加上下文的依赖注入。

//MeowvBlogEntityFrameworkCoreDbMigrationsModule.cs using Microsoft.Extensions.DependencyInjection; using Volo.Abp.Modularity; namespace Meowv.Blog.EntityFrameworkCore.DbMigrations.EntityFrameworkCore { [DependsOn( typeof(MeowvBlogFrameworkCoreModule) )] public class MeowvBlogEntityFrameworkCoreDbMigrationsModule : AbpModule { public override void ConfigureServices(ServiceConfigurationContext context) { context.Services.AddAbpDbContext<MeowvBlogMigrationsDbContext>(); } } }

MeowvBlogMigrationsDbContext和MeowvBlogDbContext没什么大的区别

//MeowvBlogMigrationsDbContext.cs using Microsoft.EntityFrameworkCore; using Volo.Abp.EntityFrameworkCore; namespace Meowv.Blog.EntityFrameworkCore.DbMigrations.EntityFrameworkCore { public class MeowvBlogMigrationsDbContext : AbpDbContext<MeowvBlogMigrationsDbContext> { public MeowvBlogMigrationsDbContext(DbContextOptions<MeowvBlogMigrationsDbContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); builder.Configure(); } } }

MeowvBlogMigrationsDbContextFactory类主要是用来使用Code-First命令的(Add-Migration 和 Update-Database ...)

需要注意的地方,我们在这里要单独设置配置文件的连接字符串,将.HttpApi.Hosting层的appsettings.json复制一份到.EntityFrameworkCore.DbMigrations,你用了什么数据库就配置什么数据库的连接字符串。

//appsettings.json { "ConnectionStrings": { "Default": "Server=localhost;User Id=root;Password=123456;Database=meowv_blog" } } //MeowvBlogMigrationsDbContextFactory.cs using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Design; using Microsoft.Extensions.Configuration; using System.IO; namespace Meowv.Blog.EntityFrameworkCore.DbMigrations.EntityFrameworkCore { public class MeowvBlogMigrationsDbContextFactory : IDesignTimeDbContextFactory<MeowvBlogMigrationsDbContext> { public MeowvBlogMigrationsDbContext CreateDbContext(string[] args) { var configuration = BuildConfiguration(); var builder = new DbContextOptionsBuilder<MeowvBlogMigrationsDbContext>() .UseMySql(configuration.GetConnectionString("Default")); return new MeowvBlogMigrationsDbContext(builder.Options); } private static IConfigurationRoot BuildConfiguration() { var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); return builder.Build(); } } }

到这里差不多就结束了,默认数据库meowv_blog_tutorial是不存在的,先去创建一个空的数据库。

2

然后在Visual Studio中打开程序包管理控制台,将.EntityFrameworkCore.DbMigrations设为启动项目。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wssfxy.html