从零开始学习ABP vNext开发 (二) 领域层

我们仍然使用《从零开始进行ABP项目开发》系列中的项目需求。

Poem需求描述

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

image

相关的数据库脚本发布在这里:Poem相关数据库表的Sql语句

增加领域层

在解决方案中增加一个新的.Net Core类库项目作为领域层,命名命名为ZL.AbpNext.Poem.Core:


图片.png

按照[从零开始学习ABP vNext开发 (一)——从控制台项目入手]中“创建Abp模块”的描述,创建新的模块,名称为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
{
    /// 
    /// 诗人,从ABP Entity派生
    /// 
    public class Poet : Entity
    {
        /// 
        /// 姓名
        /// 
        public virtual string Name { get; set; }

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

使用EF连接数据库

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

  • Microsoft.EntityFrameworkCore.SqlServer
  • Volo.Abp.EntityFrameworkCore
  • Volo.Abp.EntityFrameworkCore.SqlServer

然后,可以创建需要的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 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,IPoemDbContext
    {
        public virtual DbSet Poets { get; set; }

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

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

            //映射Poet到数据库表
            modelBuilder.Entity(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(options =>
            {
                options.AddDefaultRepositories(includeAllEntities: true);
            });

            Configure(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(options =>
            {
                options.AddDefaultRepositories(includeAllEntities: true);
            });

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

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

现在我们改造客户端,使它可以调用我们新编写的模块,访问数据库中的诗人数据。
首先,增加项目依赖项,项目结构如下:


图片.png

还需要在项目中增加appsettings.json,在配置文件中设置数据库链接字符串:

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

注意:这个文件需要设置为“如果较新则复制”


图片.png

然后,在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 repository;
        IUnitOfWorkManager uowManager;
        public Service(IRepository 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不需要修改。运行结果如下:


图片.png

小结

  • 解决方案中的每个项目都是一个ABP模块,在模块中定义模块之间的依赖关系。
  • 使用AbpApplicationFactory创建需要的模块,并调用Initialize进行模块初始化。
  • 可以使用ServiceProvider.GetService获取需要使用的对象。
  • 在模块的ConfigureServices方法中进行参数设置。

下一步工作

下一步,我们需要增加其它几个实体到Poem.Core中,并增加应用层(Application)。

你可能感兴趣的:(从零开始学习ABP vNext开发 (二) 领域层)