• Web应用开发教程 Part 7: 作家:数据库集成


    Web应用开发教程 - Part 7: 作家:数据库集成

    //[doc-params]
    {
        "UI": ["MVC","Blazor","BlazorServer","NG"],
        "DB": ["EF","Mongo"]
    }
    

    关于本教程

    在这个教程系列中,你将创建一个基于ABP的Web应用程序,叫 Acme.BookStore。这个应用程序是用来管理书籍及其作家的列表的。它是使用以下技术开发:

    • {{DB_Value}} 作为ORM的提供者。
    • {{UI_Value}} 作为UI框架。

    本教程由以下几个部分组成:

    下载源代码

    本教程根据你对UIDatabase的偏好有多个版本。我们准备了几个组合的源代码供大家下载:

    如果你在Windows上遇到 "文件名太长 "或 "解压错误",它可能与Windows的最大文件路径限制有关。Windows有一个最大的文件路径限制,即250个字符。要解决这个问题,在Windows 10中启用长路径选项

    如果你遇到与Git有关的长路径错误,可以尝试用以下命令在Windows中启用长路径。见 https://github.com/msysgit/msysgit/wiki/Git-cannot-create-a-file-or-directory-with-a-long-path
    git config --system core.longpaths true

    简介

    This part explains how to configure the database integration for the Author entity introduced in the previous part.

    这一部分解释了如何为上一部分介绍的Author实体配置数据库集成。

    {{if DB=="EF"}}

    DB Context

    打开Acme.BookStore.EntityFrameworkCore项目中的BookStoreDbContext,并添加以下DbSet属性。

    public DbSet<Author> Authors { get; set; }
    

    然后找到同一项目中的BookStoreDbContext类中的OnModelCreating方法,在该方法的末尾添加以下几行代码:

    builder.Entity<Author>(b =>
    {
        b.ToTable(BookStoreConsts.DbTablePrefix + "Authors",
            BookStoreConsts.DbSchema);
        
        b.ConfigureByConvention();
        
        b.Property(x => x.Name)
            .IsRequired()
            .HasMaxLength(AuthorConsts.MaxNameLength);
    
        b.HasIndex(x => x.Name);
    });
    

    这就像之前为Book实体所做的一样,所以不需要再做解释说明。

    创建数据库迁移

    启动解决方案被配置为使用Entity Framework Core Code First Migrations。由于我们改变了数据库映射的配置,我们应该创建一个新的迁移并对数据库进行修改。

    Acme.BookStore.EntityFrameworkCore项目的目录下打开一个命令行终端程序,并输入以下命令:

    dotnet ef migrations add Added_Authors
    

    这将为项目添加一个新的迁移类:

    bookstore-efcore-migration-authors

    你可以在同一个命令行终端中使用以下命令对数据库进行修改:

    dotnet ef database update
    

    如果你使用Visual Studio,你可能需要在包管理器控制台(PMC)中使用Add-Migration Added_Authors -c BookStoreMigrationsDbContextUpdate-Database -c BookStoreMigrationsDbContext命令。在这种情况下,确保{{if UI"MVC"}}Acme.BookStore.Web{{else if UI"BlazorServer"}}Acme.BookStore.Blazor{{else if UI"Blazor" || UI"NG"}}Acme. BookStore.HttpApi.Host{{end}}是启动项目,Acme.BookStore.EntityFrameworkCore是PMC中的默认项目

    {{else if DB=="Mongo"}}

    DB Context

    打开Acme.BookStore.MongoDb项目的MongoDb文件夹中的BookStoreMongoDbContext,向该类添加以下属性:

    public IMongoCollection<Author> Authors => Collection<Author>();
    

    {{end}}

    实现IAuthorRepository

    {{if DB=="EF"}}

    Acme.BookStore.EntityFrameworkCore项目中(在Authors文件夹中)创建一个新的类命名为EfCoreAuthorository,并粘贴以下代码:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Linq.Dynamic.Core;
    using System.Threading.Tasks;
    using Acme.BookStore.EntityFrameworkCore;
    using Microsoft.EntityFrameworkCore;
    using Volo.Abp.Domain.Repositories.EntityFrameworkCore;
    using Volo.Abp.EntityFrameworkCore;
    
    namespace Acme.BookStore.Authors
    {
        public class EfCoreAuthorRepository
            : EfCoreRepository<BookStoreDbContext, Author, Guid>,
                IAuthorRepository
        {
            public EfCoreAuthorRepository(
                IDbContextProvider<BookStoreDbContext> dbContextProvider)
                : base(dbContextProvider)
            {
            }
    
            public async Task<Author> FindByNameAsync(string name)
            {
                var dbSet = await GetDbSetAsync();
                return await dbSet.FirstOrDefaultAsync(author => author.Name == name);
            }
    
            public async Task<List<Author>> GetListAsync(
                int skipCount,
                int maxResultCount,
                string sorting,
                string filter = null)
            {
                var dbSet = await GetDbSetAsync();
                return await dbSet
                    .WhereIf(
                        !filter.IsNullOrWhiteSpace(),
                        author => author.Name.Contains(filter)
                     )
                    .OrderBy(sorting)
                    .Skip(skipCount)
                    .Take(maxResultCount)
                    .ToListAsync();
            }
        }
    }
    
    • 继承自EfCoreRepository,因此它继承了标准的存储库方法实现。
    • WhereIf是ABP框架的一个快捷的扩展方法。它只在第一个条件满足的情况下添加Where条件(它通过名称过滤,只在提供过滤器的情况下)。你可以自己做同样的事情,但是这些类型的快捷方法使我们的生活更容易。
    • sorting可以是一个字符串,如NameName ASCName DESC。通过使用System.Linq.Dynamic.Core NuGet包可以实现。

    关于基于EF Core的存储库的更多信息,请参见EF Core集成文档

    {{else if DB=="Mongo"}}

    Acme.BookStore.MongoDB项目中(在Authors文件夹中)创建一个新的类,命名为MongoDbAuthorository,并粘贴以下代码:

    using System;
    using System.Linq;
    using System.Linq.Dynamic.Core;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Acme.BookStore.MongoDB;
    using MongoDB.Driver;
    using MongoDB.Driver.Linq;
    using Volo.Abp.Domain.Repositories.MongoDB;
    using Volo.Abp.MongoDB;
    
    namespace Acme.BookStore.Authors
    {
        public class MongoDbAuthorRepository
            : MongoDbRepository<BookStoreMongoDbContext, Author, Guid>,
            IAuthorRepository
        {
            public MongoDbAuthorRepository(
                IMongoDbContextProvider<BookStoreMongoDbContext> dbContextProvider
                ) : base(dbContextProvider)
            {
            }
    
            public async Task<Author> FindByNameAsync(string name)
            {
                var queryable = await GetMongoQueryableAsync();
                return await queryable.FirstOrDefaultAsync(author => author.Name == name);
            }
    
            public async Task<List<Author>> GetListAsync(
                int skipCount,
                int maxResultCount,
                string sorting,
                string filter = null)
            {
                var queryable = await GetMongoQueryableAsync();
                return await queryable
                    .WhereIf<Author, IMongoQueryable<Author>>(
                        !filter.IsNullOrWhiteSpace(),
                        author => author.Name.Contains(filter)
                    )
                    .OrderBy(sorting)
                    .As<IMongoQueryable<Author>>()
                    .Skip(skipCount)
                    .Take(maxResultCount)
                    .ToListAsync();
            }
        }
    }
    
    • 继承自MongoDbRepository,因此它继承了标准的存储库方法实现。
    • WhereIf是ABP框架的一个快捷的扩展方法。它只在第一个条件满足的情况下添加Where条件(它通过名称过滤,只在提供过滤器的情况下)。你可以自己做同样的事情,但是这些类型的快捷方法使我们的生活更容易。
    • sorting可以是一个字符串,如NameName ASCName DESC。通过使用System.Linq.Dynamic.Core NuGet包可以实现。

    参考MongoDB集成文档以了解更多关于基于MongoDB的存储库的信息。

    {{end}}

    下一篇

    见本教程的下一篇

  • 相关阅读:
    Java 异常Exception e中e的getMessage()和toString()以及 e.printStackTrace();方法的区别
    js几秒以后倒计时跳转示例
    Java读取property配置文件
    js 设置下拉框的默认值
    JS的可枚举性
    Object的原型拷贝-create、assign、getPrototypeOf 方法的结合
    JS 事件循环机制
    vue nextTick深入理解-vue性能优化、DOM更新时机、事件循环机制
    vue 实战问题-watch 数组或者对象
    vue2.0读书笔记2-进阶
  • 原文地址:https://www.cnblogs.com/tjubuntu/p/15718040.html
Copyright © 2020-2023  润新知