基於 abp vNext 和 .NET Core 開發部落格專案 - 資料訪問和程式碼優先

阿星Plus發表於2020-05-19

上一篇文章(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。關於這點可以參考ABP文件,https://docs.abp.io/zh-Hans/abp/latest/Entities

點選檢視程式碼
//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();
            });
        }
    }
}

此時專案層級目錄如下

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>();
        }
    }
}

MeowvBlogMigrationsDbContextMeowvBlogDbContext沒什麼大的區別

//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-MigrationUpdate-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設為啟動專案。

3

鍵入命令: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

可以看到已經成功,並且生成了一個Migrations資料夾和對應的資料遷移檔案

最後輸入更新命令:Update-Database,然後開啟資料瞅瞅。

5

完美,成功建立了資料庫表,而且命名也是我們想要的,欄位型別也是ok的。__efmigrationshistory表是用來記錄遷移歷史的,這個可以不用管。當我們後續如果想要修改新增表欄位,新增表的時候,都可以使用這種方式來完成。

解決方案層級目錄圖,供參考

6

本篇使用Entity Framework Core完成資料訪問和程式碼優先的方式建立資料庫表,你學會了嗎????

開源地址:https://github.com/Meowv/Blog/tree/blog_tutorial

相關文章