(精华)2020年8月22日 ABP vNext 领域层的使用

133 阅读6分钟

Poem需求描述

我们使用一个简单的项目来说明问题,这是一款针对全唐诗的小应用,可以对唐诗和作者进行简单的查询,可以对唐诗进行自定义的分类,还有一些简单的小游戏,比如可以将一句唐诗的顺序打乱,用户进行正确的排序等。数据库已经有了,在Sql Server中,将来可能需要支持Sqlite。数据模型如下:
在这里插入图片描述
相关的数据库脚本发布在这里:Poem相关数据库表的Sql语句

增加领域层

在解决方案中增加一个新的.Net Core类库项目作为领域层,命名命名为ZL.AbpNext.Poem.Core:
在这里插入图片描述
创建新的模块,名称为PoemCoreModule:

using Volo.Abp.Modularity;

namespace ZL.AbpNext.Poem.Core
{
    public class PoemCoreModule:AbpModule
    {
    }
}

然后创建一个子目录,名称为Poems,在这个目录中创建第一个实体,名称为Poet:

using Volo.Abp.Domain.Entities;

namespace ZL.AbpNext.Poem.Core.Poems
{
    /// <summary>
    /// 诗人,从ABP Entity派生
    /// </summary>
    public class Poet : Entity<int>
    {
        /// <summary>
        /// 姓名
        /// </summary>
        public virtual string Name { get; set; }

        /// <summary>
        /// 介绍
        /// </summary>
        public virtual string Description { get; set; }
        
    }
}

使用EF连接数据库

下面,创建数据访问层,使用EF从数据库中获取数据。在解决方案中增加另一个类库项目,命名为ZL.AbpNext.Poem.EF,使用Nuget程序包管理器,安装如下程序包:

  1. Microsoft.EntityFrameworkCore.SqlServer
  2. Volo.Abp.EntityFrameworkCore
  3. Volo.Abp.EntityFrameworkCore.SqlServer
    迁移命令
Add-Migration InitialCreate
Update-database

然后,可以创建需要的DbContext,这里,Abp vNext与前一代Abp有很大的区别。
首先,需要为DbContext创建一个接口:

using Volo.Abp.Data;
using Volo.Abp.EntityFrameworkCore;
using ZL.AbpNext.Poem.Core.Poems;

namespace ZL.AbpNext.Poem.EF.EntityFramework
{
    [ConnectionStringName("Poem")]
    public interface IPoemDbContext : IEfCoreDbContext
    {
        DbSet<Poet> Poets { get; set; }
    }
}

接下来创建DbContext类:

using Microsoft.EntityFrameworkCore;
using Volo.Abp.Data;
using Volo.Abp.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore.Modeling;
using ZL.AbpNext.Poem.Core.Poems;

namespace ZL.AbpNext.Poem.EF.EntityFramework
{
    [ConnectionStringName("Poem")]
    public class PoemDbContext : AbpDbContext<PoemDbContext>,IPoemDbContext
    {
        public virtual DbSet<Poet> Poets { get; set; }

        public PoemDbContext(DbContextOptions<PoemDbContext> options) : base(options)
        {
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            //映射Poet到数据库表
            modelBuilder.Entity<Poet>(b =>
            {
                b.ToTable("Poet");
                
                //映射实体与数据库中的字段,将Id映射到数据库表的PoetID字段
                b.Property(p => p.Id)
                        .HasColumnName("PoetID");
                b.ConfigureByConvention();
            });
        }
    }
}

我们已经看到了Abp vNext在DbContext上进行的改进:1)增加了ConnectionStringName标记,可以自动从配置文件读取连接字符串信息。2)增加了DbContext的接口。

这里需要注意的是:Abp的实体都是从Entity中继承的,使用Id作为关键字标识,而我们已经存在的数据库表的关键字字段名是PoetID,这就需要在OnModelCreating中进行映射。

接下来我们创建数据模块PoemDataModule:

using Microsoft.Extensions.DependencyInjection;
using Volo.Abp.EntityFrameworkCore;
using Volo.Abp.Modularity;
using ZL.AbpNext.Poem.Core;
using ZL.AbpNext.Poem.EF.EntityFramework;

namespace ZL.AbpNext.Poem.EF
{
    [DependsOn(
    typeof(PoemCoreModule),
    typeof(AbpEntityFrameworkCoreModule)
    )]
    public class PoemDataModule:AbpModule
    {
        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            context.Services.AddAbpDbContext<PoemDbContext>(options =>
            {
                options.AddDefaultRepositories(includeAllEntities: true);
            });

            Configure<AbpDbContextOptions>(options =>
            {
                /* The main point to change your DBMS.
                 * See also BookStoreMigrationsDbContextFactory for EF Core tooling. */
                options.UseSqlServer();
            });
        }
    }
}

这里也有很大的改进,很多初始化的工作不需要在PreInitializes中进行处理,在ConfigureServices中,以更符合.Net Core的方式进行处理。这段代码为所有实体生成缺省的Repository:

context.Services.AddAbpDbContext<PoemDbContext>(options =>
{
    options.AddDefaultRepositories(includeAllEntities: true);
});

对于通用的增删改等操作,不需要再编写重复的代码。

改造控制台客户端访问数据库

现在我们改造客户端,使它可以调用我们新编写的模块,访问数据库中的诗人数据。
首先,增加项目依赖项,项目结构如下:
在这里插入图片描述
还需要在项目中增加appsettings.json,在配置文件中设置数据库链接字符串:

{
  "ConnectionStrings": {
    "Poem": "Server=localhost;Database=PoemNew;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "exclude": [
    "**/bin",
    "**/bower_components",
    "**/jspm_packages",
    "**/node_modules",
    "**/obj",
    "**/platforms"
  ]
}

在这里插入图片描述
然后,在PoemConsoleClientModel中增加对PoemCoreModule和PoemDataModule的依赖:

using Volo.Abp.Modularity;
using ZL.AbpNext.Poem.Core;
using ZL.AbpNext.Poem.EF;

namespace ZL.AbpNext.Poem.ConsoleClient
{
    [DependsOn(
    typeof(PoemCoreModule),
    typeof(PoemDataModule))]
    public class PoemConsoleClientModule:AbpModule
    {

    }
}

接下来,我们改造Service:

using System;
using System.Linq;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Uow;
using ZL.AbpNext.Poem.Core.Poems;

namespace ZL.AbpNext.Poem.ConsoleClient
{
    public class Service : ITransientDependency
    {
        IRepository<Poet> repository;
        IUnitOfWorkManager uowManager;
        public Service(IRepository<Poet> repository, IUnitOfWorkManager uowManager)
        {
            this.repository = repository;
            this.uowManager = uowManager;
        }
        public void Run()
        {
            //Console.WriteLine("你好");
            using (var uow = uowManager.Begin(new AbpUnitOfWorkOptions()))
            {
                //获取第一个诗人
                var poet = repository.FirstOrDefault();

                Console.WriteLine(poet.Name);
            }
        }
    }
}

由于框架支持依赖注入,所以,我们只需要在构造函数中增加需要的服务就可以了,不需要关心如何获取这些服务。这里我们需要Poet的repository,和执行执行工作单元的管理器,所以在构造函数中增加这两个参数。在执行方法中,就可以使用repository获取数据了。
到这里改造就完成了,主程序Program不需要修改。运行结果如下:
在这里插入图片描述

完善领域层:

现在我们创建剩下的几个实体:Poem、Category和PoemCategory实体。首先我们回顾一下已经创建的Poet实体:

using Volo.Abp.Domain.Entities;

namespace ZL.AbpNext.Poem.Core.Poems
{
    /// <summary>
    /// 诗人,从ABP Entity派生
    /// </summary>
    public class Poet : Entity<int>
    {
        /// <summary>
        /// 姓名
        /// </summary>
        public virtual string Name { get; set; }

        /// <summary>
        /// 介绍
        /// </summary>
        public virtual string Description { get; set; }
        
    }
}

实体从Entity派生,这与上一代的ABP有区别,上一代ABP中,Entity不是抽象类,缺省使用整型作为关键字类型,在新的版本中,实体必须显示声明关键字的类型。下面是几个新增加实体的代码:
分类:

using System;
using System.Collections.Generic;
using System.Text;
using Volo.Abp.Domain.Entities;

namespace ZL.AbpNext.Poem.Core.Poems
{/// <summary>
 /// 诗的分类
 /// </summary>
    public class Category : Entity<int>
    {
        /// <summary>
        /// 分类名称
        /// </summary>
        public virtual string CategoryName { get; set; }

        /// <summary>
        /// 该分类中包含的诗
        /// </summary>
        public virtual ICollection<CategoryPoem> CategoryPoems { get; set; }
    }
}

诗:

using System.Collections.Generic;
using Volo.Abp.Domain.Entities;

namespace ZL.AbpNext.Poem.Core.Poems
{
    /// <summary>
    ///
    /// Volumn和Num是全唐诗中的卷和序号,
    /// </summary>
    public class Poem : Entity<int>
    {
        /// <summary>
        /// 标题
        /// </summary>
        public virtual string Title { get; set; }

        /// <summary>
        /// 内容
        /// </summary>
        public virtual string Content { get; set; }

        /// <summary>
        /// 点评
        /// </summary>
        public virtual string Comments { get; set; }

        /// <summary>
        /// 卷(全唐诗)
        /// </summary>
        public virtual string Volumn { get; set; }

        /// <summary>
        /// 序号
        /// </summary>
        public virtual string Num { get; set; }

        /// <summary>
        /// 诗人id
        /// </summary>
        public virtual int PoetID { get; set; }

        /// <summary>
        /// 作者
        /// </summary>
        public virtual Poet Author { get; set; }


        /// <summary>
        /// 分类
        /// </summary>
        public virtual ICollection<CategoryPoem> PoemCategories { get; set; }
    }
}

诗分类连接实体:

using Volo.Abp.Domain.Entities;

namespace ZL.AbpNext.Poem.Core.Poems
{
    public class CategoryPoem : Entity<int>
    {
        public virtual int CategoryId { get; set; }

        public virtual int PoemId { get; set; }

        public virtual Category Category { get; set; }

        public virtual Poem Poem { get; set; }
    }
}

最后,在诗人中增加诗的集合:

using System.Collections.Generic;
using Volo.Abp.Domain.Entities;

namespace ZL.AbpNext.Poem.Core.Poems
{
    /// <summary>
    /// 诗人,从ABP Entity派生
    /// </summary>
    public class Poet : Entity<int>
    {
        /// <summary>
        /// 姓名
        /// </summary>
        public virtual string Name { get; set; }

        /// <summary>
        /// 介绍
        /// </summary>
        public virtual string Description { get; set; }

        /// <summary>
        /// 写的诗
        /// </summary>
        public virtual ICollection<Poem> Poems { get; set; }
    }
}

接下来,需要在EF模块中增加相应的DbSet和与数据库中表的对应关系。
IPoemDbContext:

using Microsoft.EntityFrameworkCore;
using Volo.Abp.Data;
using Volo.Abp.EntityFrameworkCore;
using ZL.AbpNext.Poem.Core.Poems;

namespace ZL.AbpNext.Poem.EF.EntityFramework
{
    [ConnectionStringName("Poem")]
    public interface IPoemDbContext : IEfCoreDbContext
    {
        DbSet<Poet> Poets { get; set; }

        DbSet<Core.Poems.Poem> Poems { get; set; }

        DbSet<Category> Categories { get; set; }

        DbSet<CategoryPoem> CategoryPoems { get; set; }
    }
}

PoemDbContext:

using Microsoft.EntityFrameworkCore;
using Volo.Abp.Data;
using Volo.Abp.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore.Modeling;
using ZL.AbpNext.Poem.Core.Poems;

namespace ZL.AbpNext.Poem.EF.EntityFramework
{
    [ConnectionStringName("Poem")]
    public class PoemDbContext : AbpDbContext<PoemDbContext>,IPoemDbContext
    {
        public  DbSet<Poet> Poets { get; set; }
        public DbSet<Core.Poems.Poem> Poems { get; set; }
        public DbSet<Category> Categories { get; set ; }
        public DbSet<CategoryPoem> CategoryPoems { get; set; }

        public PoemDbContext(DbContextOptions<PoemDbContext> options) : base(options)
        {
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            //映射Poet到数据库表
            modelBuilder.Entity<Poet>(b =>
            {
                b.ToTable("Poet");
                
                //映射实体与数据库中的字段,将Id映射到数据库表的PoetID字段
                b.Property(p => p.Id)
                        .HasColumnName("PoetID");
                b.ConfigureByConvention();
            });

            //Poem映射
            modelBuilder.Entity<Core.Poems.Poem>(b =>
            {
                b.ToTable("Poem");

                //映射实体与数据库中的字段,将Id映射到数据库表的PoetID字段
                b.Property(p => p.Id)
                        .HasColumnName("PoemId");
                //定义Poem与Poet之间的一对多关系
                b.HasOne<Poet>(s => s.Author)
                        .WithMany(s => s.Poems)
                        .HasForeignKey(s => s.PoetID);
                b.ConfigureByConvention();
            });
            //Category映射
            modelBuilder.Entity<Category>(b =>
            {
                b.ToTable("Category");

                //映射实体与数据库中的字段,将Id映射到数据库表的PoetID字段
                b.Property(p => p.Id)
                        .HasColumnName("CategoryId");
                b.ConfigureByConvention();
            });
            //CategoryPoem映射
            modelBuilder.Entity<CategoryPoem>(b =>
            {
                b.ToTable("CategoryPoem");

                //映射实体与数据库中的字段,将Id映射到数据库表的PoetID字段
                b.Property(p => p.Id)
                        .HasColumnName("CategoryPoemId");
                //定义多对多关系
                b.HasKey(t => new { t.CategoryId, t.PoemId });
                b.HasOne(pt => pt.Poem)
               .WithMany(p => p.PoemCategories)
               .HasForeignKey(pt => pt.PoemId);
                b.HasOne(pt => pt.Category)
               .WithMany(t => t.CategoryPoems)
               .HasForeignKey(pt => pt.CategoryId);
                b.ConfigureByConvention();
            });
        }
    }
}