上一篇文章(https://www.cnblogs.com/meowv/p/12909558.html)完善了項目中的代碼,接入了Swagger。本篇主要使用Entity Framework Core完成對資料庫的訪問,以及使用Code First的方式進行數據遷移,自動創建表結構。 數據訪問 在 ...
上一篇文章(https://www.cnblogs.com/meowv/p/12909558.html)完善了項目中的代碼,接入了Swagger。本篇主要使用Entity Framework Core完成對資料庫的訪問,以及使用Code-First的方式進行數據遷移,自動創建表結構。
數據訪問
在.EntityFrameworkCore
項目中添加我們的數據訪問上下文對象MeowvBlogDbContext
,繼承自 AbpDbContext<T>
。然後重寫OnModelCreating
方法。
OnModelCreating
:定義EF Core 實體映射。先調用 base.OnModelCreating
讓 abp 框架為我們實現基礎映射,然後調用builder.Configure()
擴展方法來配置應用程式的實體。當然也可以不用擴展,直接寫在裡面,這樣一大坨顯得不好看而已。
在abp框架中,可以使用 [ConnectionStringName]
Attribute 為我們的DbContext配置連接字元串名稱。先加上,然後再在appsettings.json
中進行配置,因為之前集成了多個資料庫,所以這裡我們也配置多個連接字元串,與之對應。
本項目預設採用MySql,你可以選擇任意你喜歡的。
//MeowvBlogDbContext.cs
using Microsoft.EntityFrameworkCore;
using Volo.Abp.Data;
using Volo.Abp.EntityFrameworkCore;
namespace Meowv.Blog.EntityFrameworkCore
{
[ConnectionStringName("MySql")]
public class MeowvBlogDbContext : AbpDbContext<MeowvBlogDbContext>
{
public MeowvBlogDbContext(DbContextOptions<MeowvBlogDbContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Configure();
}
}
}
//appsettings.json
{
"ConnectionStrings": {
"Enable": "MySQL",
"MySql": "Server=localhost;User Id=root;Password=123456;Database=meowv_blog_tutorial",
"SqlServer": "",
"PostgreSql": "",
"Sqlite": ""
}
}
然後新建我們的擴展類MeowvBlogDbContextModelCreatingExtensions.cs
和擴展方法Configure()
。註意,擴展方法是靜態的,需加static
//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
//AppSettings.cs
using Microsoft.Extensions.Configuration;
using System.IO;
namespace Meowv.Blog.Domain.Configurations
{
/// <summary>
/// appsettings.json配置文件數據讀取類
/// </summary>
public class AppSettings
{
/// <summary>
/// 配置文件的根節點
/// </summary>
private static readonly IConfigurationRoot _config;
/// <summary>
/// Constructor
/// </summary>
static AppSettings()
{
// 載入appsettings.json,並構建IConfigurationRoot
var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", true, true);
_config = builder.Build();
}
/// <summary>
/// EnableDb
/// </summary>
public static string EnableDb => _config["ConnectionStrings:Enable"];
/// <summary>
/// ConnectionStrings
/// </summary>
public static string ConnectionStrings => _config.GetConnectionString(EnableDb);
}
}
獲取配置文件內容比較容易,代碼中有註釋也很容易理解。
值得一提的是,ABP會自動為DbContext中的實體創建預設倉儲. 需要在註冊的時使用options添加AddDefaultRepositories()
。
預設情況下為每個實體創建一個倉儲,如果想要為其他實體也創建倉儲,可以將 includeAllEntities
設置為 true,然後就可以在服務中註入和使用 IRepository<TEntity>
或 IQueryableRepository<TEntity>
//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<MeowvBlogDbContext>(options =>
{
options.AddDefaultRepositories(includeAllEntities: true);
});
Configure<AbpDbContextOptions>(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
點擊查看代碼
//Post.cs
using System;
using Volo.Abp.Domain.Entities;
namespace Meowv.Blog.Domain.Blog
{
/// <summary>
/// Post
/// </summary>
public class Post : Entity<int>
{
/// <summary>
/// 標題
/// </summary>
public string Title { get; set; }
/// <summary>
/// 作者
/// </summary>
public string Author { get; set; }
/// <summary>
/// 鏈接
/// </summary>
public string Url { get; set; }
/// <summary>
/// HTML
/// </summary>
public string Html { get; set; }
/// <summary>
/// Markdown
/// </summary>
public string Markdown { get; set; }
/// <summary>
/// 分類Id
/// </summary>
public int CategoryId { get; set; }
/// <summary>
/// 創建時間
/// </summary>
public DateTime CreationTime { get; set; }
}
}
//Category.cs
using Volo.Abp.Domain.Entities;
namespace Meowv.Blog.Domain.Blog
{
/// <summary>
/// Category
/// </summary>
public class Category : Entity<int>
{
/// <summary>
/// 分類名稱
/// </summary>
public string CategoryName { get; set; }
/// <summary>
/// 展示名稱
/// </summary>
public string DisplayName { get; set; }
}
}
//Tag.cs
using Volo.Abp.Domain.Entities;
namespace Meowv.Blog.Domain.Blog
{
/// <summary>
/// Tag
/// </summary>
public class Tag : Entity<int>
{
/// <summary>
/// 標簽名稱
/// </summary>
public string TagName { get; set; }
/// <summary>
/// 展示名稱
/// </summary>
public string DisplayName { get; set; }
}
}
//PostTag.cs
using Volo.Abp.Domain.Entities;
namespace Meowv.Blog.Domain.Blog
{
/// <summary>
/// PostTag
/// </summary>
public class PostTag : Entity<int>
{
/// <summary>
/// 文章Id
/// </summary>
public int PostId { get; set; }
/// <summary>
/// 標簽Id
/// </summary>
public int TagId { get; set; }
}
}
//FriendLink.cs
using Volo.Abp.Domain.Entities;
namespace Meowv.Blog.Domain.Blog
{
/// <summary>
/// FriendLink
/// </summary>
public class FriendLink : Entity<int>
{
/// <summary>
/// 標題
/// </summary>
public string Title { get; set; }
/// <summary>
/// 鏈接
/// </summary>
public string LinkUrl { get; set; }
}
}
創建好實體類後,在MeowvBlogDbContext
添加DbSet屬性
//MeowvBlogDbContext.cs
...
[ConnectionStringName("MySql")]
public class MeowvBlogDbContext : AbpDbContext<MeowvBlogDbContext>
{
public DbSet<Post> Posts { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<Tag> Tags { get; set; }
public DbSet<PostTag> PostTags { get; set; }
public DbSet<FriendLink> FriendLinks { get; set; }
...
}
...
在.Domain.Shared
層添加全局常量類MeowvBlogConsts.cs
和表名常量類MeowvBlogDbConsts.cs
,搞一個表首碼的常量,我這裡寫的是meowv_
,大家可以隨意。代表我們的表名都將以meowv_
開頭。然後在MeowvBlogDbConsts
中將表名稱定義好。
//MeowvBlogConsts.cs
namespace Meowv.Blog.Domain.Shared
{
/// <summary>
/// 全局常量
/// </summary>
public class MeowvBlogConsts
{
/// <summary>
/// 資料庫表首碼
/// </summary>
public const string DbTablePrefix = "meowv_";
}
}
//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
//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<Post>(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<Category>(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<Tag>(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<PostTag>(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<FriendLink>(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();
});
}
}
}
此時項目層級目錄如下
代碼優先
在.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
是不存在的,先去創建一個空的資料庫。
然後在Visual Studio中打開程式包管理控制台,將.EntityFrameworkCore.DbMigrations
設為啟動項目。
鍵入命令: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
包,再試一遍
可以看到已經成功,並且生成了一個Migrations文件夾和對應的數據遷移文件
最後輸入更新命令:Update-Database
,然後打開數據瞅瞅。
完美,成功創建了資料庫表,而且命名也是我們想要的,欄位類型也是ok的。__efmigrationshistory
表是用來記錄遷移歷史的,這個可以不用管。當我們後續如果想要修改添加表欄位,新增表的時候,都可以使用這種方式來完成。
解決方案層級目錄圖,供參考
本篇使用Entity Framework Core完成數據訪問和代碼優先的方式創建資料庫表,你學會了嗎?