1. 程式人生 > >《ABP框架入門——第二章》簡單的查詢Demo

《ABP框架入門——第二章》簡單的查詢Demo

建立一個簡單的CURD demo,實現對一個person的查詢,後續還有增刪改。

Step 1:建立實體類(dto)

把實體類寫在Core專案中,因為實體是領域層的一部分(Core即為領域層)。

Step 2:執行資料遷移(code first)

在如下目錄下,

找到這個檔案

在BuildModel方法中新增以下程式碼:

modelBuilder.Entity("SojsDemo.Demo.Person", b =>
                {
                    //自增的主鍵id,是entity生成的
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd()
                        .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

                    //姓名
                    b.Property<string>("Name");

                    //設定id為主鍵
                    b.HasKey("Id");

                    //表名
                    b.ToTable("People");
                });

然後在PM中執行 ,‘PeopleInitialCreate’是檔案的名字。此時會生成下面的兩個檔案:

,修改第一個檔案,如下:

protected override void Up(MigrationBuilder migrationBuilder)
        {
            //建表邏輯
            migrationBuilder.CreateTable(
                //表名
               name: "AbpPeople",
               //Column,欄位名
               columns: table => new
               {
                   Id = table.Column<int>(nullable: false),
                   Name = table.Column<string>(nullable: false),
               },
               //約束,這裡只有一個主鍵約束
               constraints: table =>
               {
                   table.PrimaryKey("PK_AppEvents", x => x.Id);
               });

        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            //刪除表的邏輯,暫時用不到
            migrationBuilder.DropTable(
                name: "AbpPeople");
        }

然後執行update-database,開啟sqlserver資源管理器,找到你的資料庫,可以看到已經生成了對應的表:

Step 3: Respository層(倉儲層)

在如下位置建立Person的倉儲介面IPersonRepository:

接下來實現介面,將寫在EntityFrameworkCore專案中,這是我們的資料持久化層,程式碼如下:

public class PersonRepository : SojsDemoRepositoryBase<Person, int>, IPersonRepository
    {
        public readonly IRepository<Person> _personRepository;
        protected PersonRepository(IDbContextProvider<SojsDemoDbContext> dbContextProvider) : base(dbContextProvider)
        {
        }
        public List<Person> GetAllPerson()
        {
            return _personRepository.GetAllList();
        }
    }

這裡繼承了一個框架的基類,其中以及幫我們實現了一些常用的CURD方法,今後如果有通用方法,也可以寫在這個類中。

關於訪問級別的提醒,請把類定義為public

Step 4:Application Service層

在application專案中建立Demo資料夾,結構和內容如下:

其中Dto為應用層的資料傳輸物件,對應為業務層的model,內容如下:

public class GetAllPersonOutput
    {
        public GetAllPersonOutput(int id, string name)
        {
            this.Id = id;
            this.Name = name;
        }
        public int Id { get; set; }
        public string Name { get; set; }
    }

然後分別是應用服務介面和實現類:

/// <summary>
    /// 繼承IApplicationService介面
    /// </summary>
    public interface IPersonAppService : IApplicationService
    {
        //定義一個方法
        List<GetAllPersonOutput> GetAllPerson();
    }
/// <summary>
    /// 實現IPersonAppService介面
    /// </summary>
    public class PersonAppService : IPersonAppService
    {
        //通過建構函式注入IPersonRepository,也可通過屬性注入,詳情檢視學習資料或官方文件
        public readonly IPersonRepository _personRepository;
        //實現介面中的方法
        public List<GetAllPersonOutput> GetAllPerson()
        {
            List<GetAllPersonOutput> resultSet = new List<GetAllPersonOutput>();
            List<Person> people = _personRepository.GetAllPerson();
            foreac(Person item in people){
                resultSet.Add(new GetAllPersonOutput(item.Id, item.Name));
            }
            return resultSet;
        }
    }

到此,Demo的後端已經完成,我們提供了一個Web API介面供前端呼叫獲取資料,swaggerUI顯示如下:

過兩天我看一下vue.js基礎,寫一個前端呼叫這個api的demo。

OK總結一下:

首先建立領域層的model,並且在此定義IRepository介面。之後我們在EntityFrameworkCore中實現我們剛剛定義的IRepository介面。到此我們領域模型這裡完成。然後去寫應用服務層,首先定義需要的業務傳輸物件,與領域層的model對應(當然有特殊業務需求時是不同的),然後是應用服務介面與實現類。到此一個簡單的demo完成了。

ps:關於web api,是框架自動幫我們生成的,官方文件的程式碼如下:

Configuration.Modules.AbpAspNetCore().CreateControllersForAppServices(typeof(MyApplicationModule).Assembly, moduleName: 'app', useConventionalHttpVerbs: true);

這句程式碼對於在我們的demo中是:

,在這個類的預初始化方法中,如下:

public override void PreInitialize()
        {
            Configuration.DefaultNameOrConnectionString = _appConfiguration.GetConnectionString(
                SojsDemoConsts.ConnectionStringName
            );

            // Use database for language management
            Configuration.Modules.Zero().LanguageManagement.EnableDbLocalization();

            Configuration.Modules.AbpAspNetCore()
                 .CreateControllersForAppServices(
                     typeof(SojsDemoApplicationModule).GetAssembly()
                 );

            ConfigureTokenAuth();
        }

這裡的註冊也是由框架去完成的,感興趣可以檢視官方文件