基於 abp vNext 和 .NET Core 開發部落格專案 - 資料訪問和程式碼優先
阿新 • • 發佈:2020-05-19
上一篇文章(https://www.cnblogs.com/meowv/p/12909558.html)完善了專案中的程式碼,接入了Swagger。本篇主要使用Entity Framework Core完成對資料庫的訪問,以及使用Code-First的方式進行資料遷移,自動建立表結構。
## 資料訪問
在`.EntityFrameworkCore`專案中新增我們的資料訪問上下文物件`MeowvBlogDbContext`,繼承自 `AbpDbContext`。然後重寫`OnModelCreating`方法。
`OnModelCreating`:定義EF Core 實體對映。先呼叫 `base.OnModelCreating` 讓 abp 框架為我們實現基礎對映,然後呼叫`builder.Configure()`擴充套件方法來配置應用程式的實體。當然也可以不用擴充套件,直接寫在裡面,這樣一大坨顯得不好看而已。
在abp框架中,可以使用 `[ConnectionStringName]` Attribute 為我們的DbContext配置連線字串名稱。先加上,然後再在`appsettings.json`中進行配置,因為之前集成了多個數據庫,所以這裡我們也配置多個連線字串,與之對應。
本專案預設採用MySql,你可以選擇任意你喜歡的。
```CSharp
//MeowvBlogDbContext.cs
using Microsoft.EntityFrameworkCore;
using Volo.Abp.Data;
using Volo.Abp.EntityFrameworkCore;
namespace Meowv.Blog.EntityFrameworkCore
{
[ConnectionStringName("MySql")]
public class MeowvBlogDbContext : AbpDbContext
{
public MeowvBlogDbContext(DbContextOptions options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Configure();
}
}
}
```
```json
//appsettings.json
{
"ConnectionStrings": {
"Enable": "MySQL",
"MySql": "Server=localhost;User Id=root;Password=123456;Database=meowv_blog_tutorial",
"SqlServer": "",
"PostgreSql": "",
"Sqlite": ""
}
}
```
然後新建我們的擴充套件類`MeowvBlogDbContextModelCreatingExtensions.cs`和擴充套件方法`Configure()`。注意,擴充套件方法是靜態的,需加`static`
```CSharp
//MeowvBlogDbContextModelCreatingExtensions.cs
using Microsoft.EntityFrameworkCore;
using Volo.Abp;
namespace Meowv.Blog.EntityFrameworkCore
{
public static class MeowvBlogDbContextModelCreatingExtensions
{
public static void Configure(this ModelBuilder builder)
{
Check.NotNull(builder, nameof(builder));
...
}
}
}
```
完成上述操作後在我們的模組類`MeowvBlogFrameworkCoreModule`中將DbContext註冊到依賴注入,根據你配置的值使用不同的資料庫。在`.Domain`層建立配置檔案訪問類`AppSettings.cs`
```CSharp
//AppSettings.cs
using Microsoft.Extensions.Configuration;
using System.IO;
namespace Meowv.Blog.Domain.Configurations
{
///
/// appsettings.json配置檔案資料讀取類
///
public class AppSettings
{
///
/// 配置檔案的根節點
///
private static readonly IConfigurationRoot _config;
///
/// Constructor
///
static AppSettings()
{
// 載入appsettings.json,並構建IConfigurationRoot
var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", true, true);
_config = builder.Build();
}
///
/// EnableDb
///
public static string EnableDb => _config["ConnectionStrings:Enable"];
///
/// ConnectionStrings
///
public static string ConnectionStrings => _config.GetConnectionString(EnableDb);
}
}
```
獲取配置檔案內容比較容易,程式碼中有註釋也很容易理解。
值得一提的是,ABP會自動為DbContext中的實體建立預設倉儲. 需要在註冊的時使用options新增`AddDefaultRepositories()`。
預設情況下為每個實體建立一個倉儲,如果想要為其他實體也建立倉儲,可以將 `includeAllEntities` 設定為 true,然後就可以在服務中注入和使用 `IRepository` 或 `IQueryableRepository`
```CSharp
//MeowvBlogFrameworkCoreModule.cs
using Meowv.Blog.Domain;
using Meowv.Blog.Domain.Configurations;
using Microsoft.Extensions.DependencyInjection;
using Volo.Abp.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore.MySQL;
using Volo.Abp.EntityFrameworkCore.PostgreSql;
using Volo.Abp.EntityFrameworkCore.Sqlite;
using Volo.Abp.EntityFrameworkCore.SqlServer;
using Volo.Abp.Modularity;
namespace Meowv.Blog.EntityFrameworkCore
{
[DependsOn(
typeof(MeowvBlogDomainModule),
typeof(AbpEntityFrameworkCoreModule),
typeof(AbpEntityFrameworkCoreMySQLModule),
typeof(AbpEntityFrameworkCoreSqlServerModule),
typeof(AbpEntityFrameworkCorePostgreSqlModule),
typeof(AbpEntityFrameworkCoreSqliteModule)
)]
public class MeowvBlogFrameworkCoreModule : AbpModule
{
public override void ConfigureServices(ServiceConfigurationContext context)
{
context.Services.AddAbpDbContext(options =>
{
options.AddDefaultRepositories(includeAllEntities: true);
});
Configure(options =>
{
switch (AppSettings.EnableDb)
{
case "MySQL":
options.UseMySQL();
break;
case "SqlServer":
options.UseSqlServer();
break;
case "PostgreSql":
options.UsePostgreSql();
break;
case "Sqlite":
options.UseSqlite();
break;
default:
options.UseMySQL();
break;
}
});
}
}
}
```
現在可以來初步設計部落格所需表為:發表文章表(posts)、分類表(categories)、標籤表(tags)、文章對應標籤表(post_tags)、友情連結表(friendlinks)
在`.Domain`層編寫實體類,Post.cs、Category.cs、Tag.cs、PostTag.cs、FriendLink.cs。把主鍵設定為int型,直接繼承Entity。關於這點可以參考ABP文件,https://docs.abp.io/zh-Hans/abp/latest/Entities
```CSharp
//Post.cs
using System;
using Volo.Abp.Domain.Entities;
namespace Meowv.Blog.Domain.Blog
{
///
{
///
{
///
{
///
{
///
{
///
建立好實體類後,在`MeowvBlogDbContext`新增DbSet屬性
```CSharp
//MeowvBlogDbContext.cs
...
[ConnectionStringName("MySql")]
public class MeowvBlogDbContext : AbpDbContext
{
public DbSet Posts { get; set; }
public DbSet Categories { get; set; }
public DbSet Tags { get; set; }
public DbSet PostTags { get; set; }
public DbSet FriendLinks { get; set; }
...
}
...
```
在`.Domain.Shared`層新增全域性常量類`MeowvBlogConsts.cs`和表名常量類`MeowvBlogDbConsts.cs`,搞一個表字首的常量,我這裡寫的是`meowv_`,大家可以隨意。代表我們的表名都將以`meowv_`開頭。然後在`MeowvBlogDbConsts`中將表名稱定義好。
```CSharp
//MeowvBlogConsts.cs
namespace Meowv.Blog.Domain.Shared
{
///
/// 全域性常量
///
public class MeowvBlogConsts
{
///
/// 資料庫表字首
///
public const string DbTablePrefix = "meowv_";
}
}
```
```CSharp
//MeowvBlogDbConsts.cs
namespace Meowv.Blog.Domain.Shared
{
public class MeowvBlogDbConsts
{
public static class DbTableName
{
public const string Posts = "Posts";
public const string Categories = "Categories";
public const string Tags = "Tags";
public const string PostTags = "Post_Tags";
public const string Friendlinks = "Friendlinks";
}
}
}
```
在`Configure()`方法中配置表模型,包括表名、欄位型別和長度等資訊。對於下面程式碼不是很明白的可以看看微軟的自定義 Code First 約定:https://docs.microsoft.com/zh-cn/ef/ef6/modeling/code-first/conventions/custom
```CSharp
//MeowvBlogDbContextModelCreatingExtensions.cs
using Meowv.Blog.Domain.Blog;
using Meowv.Blog.Domain.Shared;
using Microsoft.EntityFrameworkCore;
using Volo.Abp;
using static Meowv.Blog.Domain.Shared.MeowvBlogDbConsts;
namespace Meowv.Blog.EntityFrameworkCore
{
public static class MeowvBlogDbContextModelCreatingExtensions
{
public static void Configure(this ModelBuilder builder)
{
Check.NotNull(builder, nameof(builder));
builder.Entity(b =>
{
b.ToTable(MeowvBlogConsts.DbTablePrefix + DbTableName.Posts);
b.HasKey(x => x.Id);
b.Property(x => x.Title).HasMaxLength(200).IsRequired();
b.Property(x => x.Author).HasMaxLength(10);
b.Property(x => x.Url).HasMaxLength(100).IsRequired();
b.Property(x => x.Html).HasColumnType("longtext").IsRequired();
b.Property(x => x.Markdown).HasColumnType("longtext").IsRequired();
b.Property(x => x.CategoryId).HasColumnType("int");
b.Property(x => x.CreationTime).HasColumnType("datetime");
});
builder.Entity(b =>
{
b.ToTable(MeowvBlogConsts.DbTablePrefix + DbTableName.Categories);
b.HasKey(x => x.Id);
b.Property(x => x.CategoryName).HasMaxLength(50).IsRequired();
b.Property(x => x.DisplayName).HasMaxLength(50).IsRequired();
});
builder.Entity(b =>
{
b.ToTable(MeowvBlogConsts.DbTablePrefix + DbTableName.Tags);
b.HasKey(x => x.Id);
b.Property(x => x.TagName).HasMaxLength(50).IsRequired();
b.Property(x => x.DisplayName).HasMaxLength(50).IsRequired();
});
builder.Entity(b =>
{
b.ToTable(MeowvBlogConsts.DbTablePrefix + DbTableName.PostTags);
b.HasKey(x => x.Id);
b.Property(x => x.PostId).HasColumnType("int").IsRequired();
b.Property(x => x.TagId).HasColumnType("int").IsRequired();
});
builder.Entity(b =>
{
b.ToTable(MeowvBlogConsts.DbTablePrefix + DbTableName.Friendlinks);
b.HasKey(x => x.Id);
b.Property(x => x.Title).HasMaxLength(20).IsRequired();
b.Property(x => x.LinkUrl).HasMaxLength(100).IsRequired();
});
}
}
}
```
此時專案層級目錄如下
![1](https://img2020.cnblogs.com/blog/891843/202005/891843-20200518222720250-371775560.png)
## 程式碼優先
在`.EntityFrameworkCore.DbMigrations`中新建模組類`MeowvBlogEntityFrameworkCoreDbMigrationsModule.cs`、資料遷移上下文訪問物件`MeowvBlogMigrationsDbContext.cs`和一個Design Time Db Factory類`MeowvBlogMigrationsDbContextFactory.cs`
模組類依賴`MeowvBlogFrameworkCoreModule`模組和`AbpModule`。並在`ConfigureServices`方法中新增上下文的依賴注入。
```CSharp
//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`和`MeowvBlogDbContext`沒什麼大的區別
```CSharp
//MeowvBlogMigrationsDbContext.cs
using Microsoft.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore;
namespace Meowv.Blog.EntityFrameworkCore.DbMigrations.EntityFrameworkCore
{
public class MeowvBlogMigrationsDbContext : AbpDbContext
{
public MeowvBlogMigrationsDbContext(DbContextOptions 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`,你用了什麼資料庫就配置什麼資料庫的連線字串。
```json
//appsettings.json
{
"ConnectionStrings": {
"Default": "Server=localhost;User Id=root;Password=123456;Database=meowv_blog"
}
}
```
```CSharp
//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
{
public MeowvBlogMigrationsDbContext CreateDbContext(string[] args)
{
var configuration = BuildConfiguration();
var builder = new DbContextOptionsBuilder()
.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](https://img2020.cnblogs.com/blog/891843/202005/891843-20200518224704263-241593676.png)
然後在Visual Studio中開啟程式包管理控制檯,將`.EntityFrameworkCore.DbMigrations`設為啟動專案。
![3](https://img2020.cnblogs.com/blog/891843/202005/891843-20200518224833467-1959921804.png)
鍵入命令:`Add-Migration Initial`,會發現報錯啦,錯誤資訊如下:
```
Add-Migration : 無法將“Add-Migration”項識別為 cmdlet、函式、指令碼檔案或可執行程式的名稱。請檢查名稱的拼寫,如果包括路徑,請確保路徑正確,然後再試一次。
所在位置 行:1 字元: 1
+ Add-Migration Initial
+ ~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Add-Migration:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
```
這是因為我們少添加了一個包,要使用程式碼優先方式遷移資料,必須新增,`Microsoft.EntityFrameworkCore.Tools`。
緊接著直接用命令安裝`Install-Package Microsoft.EntityFrameworkCore.Tools`包,再試一遍
![4](https://img2020.cnblogs.com/blog/891843/202005/891843-20200518225618304-1296718119.png)
可以看到已經成功,並且生成了一個Migrations資料夾和對應的資料遷移檔案
最後輸入更新命令:`Update-Database`,然後開啟資料瞅瞅。
![5](https://img2020.cnblogs.com/blog/891843/202005/891843-20200518230144006-254504217.png)
完美,成功建立了資料庫表,而且命名也是我們想要的,欄位型別也是ok的。`__efmigrationshistory`表是用來記錄遷移歷史的,這個可以不用管。當我們後續如果想要修改新增表字段,新增表的時候,都可以使用這種方式來完成。
解決方案層級目錄圖,供參考
![6](https://img2020.cnblogs.com/blog/891843/202005/891843-20200518231410716-1109583030.png)
本篇使用Entity Framework Core完成資料訪問和程式碼優先的方式建立資料庫表,你學會了嗎?