Web应用程序开发教程 - 第十章: 图书到作者的关系
关于本教程
在本系列教程中, 你将构建一个名为 Acme.BookStore
的用于管理书籍及其作者列表的基于ABP的应用程序. 它是使用以下技术开发的:
- **** 做为ORM提供程序.
- Blazor Server 做为UI框架.
本教程分为以下部分:
- Part 1: 创建服务端
- Part 2: 图书列表页面
- Part 3: 创建,更新和删除图书
- Part 4: 集成测试
- Part 5: 授权
- Part 6: 作者: 领域层
- Part 7: 作者: 数据库集成
- Part 8: 作者: 应用服务层
- Part 9: 作者: 用户页面
- Part 10: 图书到作者的关系 (本章)
下载源码
本教程根据你的UI 和 数据库偏好有多个版本,我们准备了几种可供下载的源码组合:
如果你在Windows中遇到 "文件名太长" or "解压错误", 很可能与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
简介
我们已经为图书管理应用程序创建了 图书
和 作者
功能. 然而, 这些实体间还没有关联.
在本章, 我们会在 作者
和 图书
实体间建立 1 对 N 的关系.
在图书实体中加入关系
打开 Acme.BookStore.Domain
项目中的 Books/Book.cs
, 在 Book
实体中加入下列属性:
public Guid AuthorId { get; set; }
数据库 & 数据迁移
为 Book
实体新增一个不为空的 AuthorId
属性. 但是, 数据库中已存在的图书怎么办? 它们没有 AuthorId
s, 当我们尝试运行应用程序时会出问题.
这是一个 典型的迁移问题, 解决方案依赖于你的具体情况;
- 如果你还没有发布应用程序到生产环境, 你可以直接删除数据库中的图书数据, 甚至你可以删除开发环境中的整个数据库.
- 你可以在数据迁移或生成种子阶段使用代码更新已有数据.
- 你可以手工处理这些数据.
我们倾向于 删除数据库 , 因为这只是个示例项目, 数据丢失并不要紧. 因为这个主题不是关于ABP框架的, 我们不会深入所有的场景.
修改数据种子
因为 AuthorId
是 Book
实体的不可为空属性, 当前的数据种子代码不能工作. 打开 Acme.BookStore.Domain
项目中的 BookStoreDataSeederContributor
, 修改成以下代码:
using System;
using System.Threading.Tasks;
using Acme.BookStore.Authors;
using Acme.BookStore.Books;
using Volo.Abp.Data;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Repositories;
namespace Acme.BookStore
{
public class BookStoreDataSeederContributor
: IDataSeedContributor, ITransientDependency
{
private readonly IRepository<Book, Guid> _bookRepository;
private readonly IAuthorRepository _authorRepository;
private readonly AuthorManager _authorManager;
public BookStoreDataSeederContributor(
IRepository<Book, Guid> bookRepository,
IAuthorRepository authorRepository,
AuthorManager authorManager)
{
_bookRepository = bookRepository;
_authorRepository = authorRepository;
_authorManager = authorManager;
}
public async Task SeedAsync(DataSeedContext context)
{
if (await _bookRepository.GetCountAsync() > 0)
{
return;
}
var orwell = await _authorRepository.InsertAsync(
await _authorManager.CreateAsync(
"George Orwell",
new DateTime(1903, 06, 25),
"Orwell produced literary criticism and poetry, fiction and polemical journalism; and is best known for the allegorical novella Animal Farm (1945) and the dystopian novel Nineteen Eighty-Four (1949)."
)
);
var douglas = await _authorRepository.InsertAsync(
await _authorManager.CreateAsync(
"Douglas Adams",
new DateTime(1952, 03, 11),
"Douglas Adams was an English author, screenwriter, essayist, humorist, satirist and dramatist. Adams was an advocate for environmentalism and conservation, a lover of fast cars, technological innovation and the Apple Macintosh, and a self-proclaimed 'radical atheist'."
)
);
await _bookRepository.InsertAsync(
new Book
{
AuthorId = orwell.Id, // SET THE AUTHOR
Name = "1984",
Type = BookType.Dystopia,
PublishDate = new DateTime(1949, 6, 8),
Price = 19.84f
},
autoSave: true
);
await _bookRepository.InsertAsync(
new Book
{
AuthorId = douglas.Id, // SET THE AUTHOR
Name = "The Hitchhiker's Guide to the Galaxy",
Type = BookType.ScienceFiction,
PublishDate = new DateTime(1995, 9, 27),
Price = 42.0f
},
autoSave: true
);
}
}
}
唯一的区别是设置 Book
实体的 AuthorId
属性.
执行
DbMigrator
前删除已有图书或数据库. 参阅上面的 数据库 & 数据迁移 小节获取详细信息.
你现在可以运行 .DbMigrator
控制台应用程序, 迁移 数据库 schema 并生成 种子 初始数据.
应用层
我们将修改 BookAppService
, 支持作者关系.
数据传输对象
让我们从DTOs开始.
BookDto
打开 Acme.BookStore.Application.Contracts
项目的 Books
文件夹下的 BookDto
类, 添加如下属性:
public Guid AuthorId { get; set; }
public string AuthorName { get; set; }
最终的 BookDto
类应该如下:
using System;
using Volo.Abp.Application.Dtos;
namespace Acme.BookStore.Books
{
public class BookDto : AuditedEntityDto<Guid>
{
public Guid AuthorId { get; set; }
public string AuthorName { get; set; }
public string Name { get; set; }
public BookType Type { get; set; }
public DateTime PublishDate { get; set; }
public float Price { get; set; }
}
}
CreateUpdateBookDto
打开 Acme.BookStore.Application.Contracts
项目的 Books
文件夹下的 CreateUpdateBookDto
类, 添加 AuthorId
属性:
public Guid AuthorId { get; set; }
AuthorLookupDto
在 Acme.BookStore.Application.Contracts
项目的 Books
文件夹下新建一个类 AuthorLookupDto
:
using System;
using Volo.Abp.Application.Dtos;
namespace Acme.BookStore.Books
{
public class AuthorLookupDto : EntityDto<Guid>
{
public string Name { get; set; }
}
}
它会被一个将要添加到 IBookAppService
的新方法使用.
IBookAppService
打开 Acme.BookStore.Application.Contracts
项目的 Books
文件夹下的 IBookAppService
接口, 添加一个名为 GetAuthorLookupAsync
的新方法:
using System;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
namespace Acme.BookStore.Books
{
public interface IBookAppService :
ICrudAppService< //Defines CRUD methods
BookDto, //Used to show books
Guid, //Primary key of the book entity
PagedAndSortedResultRequestDto, //Used for paging/sorting
CreateUpdateBookDto> //Used to create/update a book
{
// ADD the NEW METHOD
Task<ListResultDto<AuthorLookupDto>> GetAuthorLookupAsync();
}
}
这个新方法将被UI用来获取作者列表, 填充一个下拉框. 使用这个下拉框选择图书作者.
BookAppService
打开 Acme.BookStore.Application
项目的 Books
文件夹下的 BookAppService
类, 更新为以下代码:
using System;
using System.Collections.Generic;
using System.Linq.Dynamic.Core;
using System.Linq;
using System.Threading.Tasks;
using Acme.BookStore.Authors;
using Acme.BookStore.Permissions;
using Microsoft.AspNetCore.Authorization;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
namespace Acme.BookStore.Books
{
[Authorize(BookStorePermissions.Books.Default)]
public class BookAppService :
CrudAppService<
Book, //The Book entity
BookDto, //Used to show books
Guid, //Primary key of the book entity
PagedAndSortedResultRequestDto, //Used for paging/sorting
CreateUpdateBookDto>, //Used to create/update a book
IBookAppService //implement the IBookAppService
{
private readonly IAuthorRepository _authorRepository;
public BookAppService(
IRepository<Book, Guid> repository,
IAuthorRepository authorRepository)
: base(repository)
{
_authorRepository = authorRepository;
GetPolicyName = BookStorePermissions.Books.Default;
GetListPolicyName = BookStorePermissions.Books.Default;
CreatePolicyName = BookStorePermissions.Books.Create;
UpdatePolicyName = BookStorePermissions.Books.Edit;
DeletePolicyName = BookStorePermissions.Books.Create;
}
public async override Task<BookDto> GetAsync(Guid id)
{
var book = await Repository.GetAsync(id);
var bookDto = ObjectMapper.Map<Book, BookDto>(book);
var author = await _authorRepository.GetAsync(book.AuthorId);
bookDto.AuthorName = author.Name;
return bookDto;
}
public async override Task<PagedResultDto<BookDto>>
GetListAsync(PagedAndSortedResultRequestDto input)
{
//Set a default sorting, if not provided
if (input.Sorting.IsNullOrWhiteSpace())
{
input.Sorting = nameof(Book.Name);
}
//Get the IQueryable<Book> from the repository
var queryable = await Repository.GetQueryableAsync();
//Get the books
var books = await AsyncExecuter.ToListAsync(
queryable
.OrderBy(input.Sorting)
.Skip(input.SkipCount)
.Take(input.MaxResultCount)
);
//Convert to DTOs
var bookDtos = ObjectMapper.Map<List<Book>, List<BookDto>>(books);
//Get a lookup dictionary for the related authors
var authorDictionary = await GetAuthorDictionaryAsync(books);
//Set AuthorName for the DTOs
bookDtos.ForEach(bookDto => bookDto.AuthorName =
authorDictionary[bookDto.AuthorId].Name);
//Get the total count with another query (required for the paging)
var totalCount = await Repository.GetCountAsync();
return new PagedResultDto<BookDto>(
totalCount,
bookDtos
);
}
public async Task<ListResultDto<AuthorLookupDto>> GetAuthorLookupAsync()
{
var authors = await _authorRepository.GetListAsync();
return new ListResultDto<AuthorLookupDto>(
ObjectMapper.Map<List<Author>, List<AuthorLookupDto>>(authors)
);
}
private async Task<Dictionary<Guid, Author>>
GetAuthorDictionaryAsync(List<Book> books)
{
var authorIds = books
.Select(b => b.AuthorId)
.Distinct()
.ToArray();
var queryable = await _authorRepository.GetQueryableAsync();
var authors = await AsyncExecuter.ToListAsync(
queryable.Where(a => authorIds.Contains(a.Id))
);
return authors.ToDictionary(x => x.Id, x => x);
}
}
}
我们做了以下修改:
- 给所有新建/覆写的方法增加
[Authorize(BookStorePermissions.Books.Default)]
进行授权(当授权特性应用于类时, 它对这个类的所有方法有效). - 注入
IAuthorRepository
, 从作者中查询. - 覆写基类
CrudAppService
的GetAsync
方法. 这个方法根据给定的id
返回单一BookDto
对象. - 覆写
CrudAppService
基类的GetListAsync
方法, 返回图书列表. 这里将从数据库中查询作者和在应用层设置作者名进行了分离. 你也可以创建一个自定义repository方法, 执行一个join查询, 或者利用MongoDB AP在一个查询中获取图书的作者, 这种做法性能会更好. - 新建一个方法:
GetAuthorLookupAsync
. 这个方法只是简单地获取所有作者. UI使用这个方法填充一个下拉框, 当编辑图书时用来选择作者.
对象到对象映射映射
引入 AuthorLookupDto
类, 在 GetAuthorLookupAsync
方法中使用对象映射. 所以, 我们需要在 Acme.BookStore.Application
项目的 BookStoreApplicationAutoMapperProfile.cs
文件中加入一个新的映射定义.
CreateMap<Author, AuthorLookupDto>();
单元测试
因为修改了 AuthorAppService
, 一些单元测试失败了. 打开 Acme.BookStore.Application.Tests
项目的 Books
目录中的 BookAppService_Tests
, 修改成以下代码:
using System;
using System.Linq;
using System.Threading.Tasks;
using Acme.BookStore.Authors;
using Shouldly;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Modularity;
using Volo.Abp.Validation;
using Xunit;
namespace Acme.BookStore.Books;
public abstract class BookAppService_Tests<TStartupModule> : BookStoreApplicationTestBase<TStartupModule>
where TStartupModule : IAbpModule
{
private readonly IBookAppService _bookAppService;
private readonly IAuthorAppService _authorAppService;
protected BookAppService_Tests()
{
_bookAppService = GetRequiredService<IBookAppService>();
_authorAppService = GetRequiredService<IAuthorAppService>();
}
[Fact]
public async Task Should_Get_List_Of_Books()
{
//Act
var result = await _bookAppService.GetListAsync(
new PagedAndSortedResultRequestDto()
);
//Assert
result.TotalCount.ShouldBeGreaterThan(0);
result.Items.ShouldContain(b => b.Name == "1984" &&
b.AuthorName == "George Orwell");
}
[Fact]
public async Task Should_Create_A_Valid_Book()
{
var authors = await _authorAppService.GetListAsync(new GetAuthorListDto());
var firstAuthor = authors.Items.First();
//Act
var result = await _bookAppService.CreateAsync(
new CreateUpdateBookDto
{
AuthorId = firstAuthor.Id,
Name = "New test book 42",
Price = 10,
PublishDate = System.DateTime.Now,
Type = BookType.ScienceFiction
}
);
//Assert
result.Id.ShouldNotBe(Guid.Empty);
result.Name.ShouldBe("New test book 42");
}
[Fact]
public async Task Should_Not_Create_A_Book_Without_Name()
{
var exception = await Assert.ThrowsAsync<AbpValidationException>(async () =>
{
await _bookAppService.CreateAsync(
new CreateUpdateBookDto
{
Name = "",
Price = 10,
PublishDate = DateTime.Now,
Type = BookType.ScienceFiction
}
);
});
exception.ValidationErrors
.ShouldContain(err => err.MemberNames.Any(m => m == "Name"));
}
}
- 修改
Should_Get_List_Of_Books
中的断言条件, 从b => b.Name == "1984"
修改为b => b.Name == "1984" && b.AuthorName == "George Orwell"
, 检查用户名是否被填充. - 修改
Should_Create_A_Valid_Book
方法, 当新建图书时, 设置AuthorId
, 因为它现在是不可为空的了.
用户页面
The Book List
在图书列表上显示 作者姓名 非常容易. 打开 Acme.BookStore.Blazor
项目中的 the /Pages/Books.razor
文件, 在 名称
(图书名) 列后加入下列 DataGridColumn
定义:
<DataGridColumn TItem="BookDto"
Field="@nameof(BookDto.AuthorName)"
Caption="@L["Author"]"></DataGridColumn>
运行应用程序, 你将在表格上看到 作者 列:
新建图书模态窗口
在 Books.razor
文件的 @code
小节加入以下成员变量:
IReadOnlyList<AuthorLookupDto> authorList = Array.Empty<AuthorLookupDto>();
覆写 OnInitializedAsync
方法, 加入以下代码:
protected override async Task OnInitializedAsync()
{
await base.OnInitializedAsync();
authorList = (await AppService.GetAuthorLookupAsync()).Items;
}
- 调用
base.OnInitializedAsync()
是有必要的, 因为AbpCrudPageBase
有一些初始化代码要执行.
最终的 @code
代码如下:
@code
{
//ADDED A NEW FIELD
IReadOnlyList<AuthorLookupDto> authorList = Array.Empty<AuthorLookupDto>();
public Books() // Constructor
{
CreatePolicyName = BookStorePermissions.Books.Create;
UpdatePolicyName = BookStorePermissions.Books.Edit;
DeletePolicyName = BookStorePermissions.Books.Delete;
}
//GET AUTHORS ON INITIALIZATION
protected override async Task OnInitializedAsync()
{
await base.OnInitializedAsync();
authorList = (await AppService.GetAuthorLookupAsync()).Items;
}
}
最后, 在 新建 模态窗口的 ModalBody
加入以下 Field
定义, 在 Name
field之前, 做为第一项:
<Field>
<FieldLabel>@L["Author"]</FieldLabel>
<Select TValue="Guid" @bind-SelectedValue="@NewEntity.AuthorId">
<SelectItem TValue="Guid" Value="Guid.Empty">@L["PickAnAuthor"]</SelectItem>
@foreach (var author in authorList)
{
<SelectItem TValue="Guid" Value="@author.Id">
@author.Name
</SelectItem>
}
</Select>
</Field>
这需要在 en.json
文件中加入一个新的本地化键:
"PickAnAuthor": "Pick an author"
你可以运行应用程序, 当新建图书时, 可以看见 作者选择:
编辑图书模态窗口
在 编辑 模态窗口的 ModalBody
加入以下 Field
定义, 在 Name
field之前, 做为第一项:
<Field>
<FieldLabel>@L["Author"]</FieldLabel>
<Select TValue="Guid" @bind-SelectedValue="@EditingEntity.AuthorId">
@foreach (var author in authorList)
{
<SelectItem TValue="Guid" Value="@author.Id">
@author.Name
</SelectItem>
}
</Select>
</Field>
这就是全部了. 我们重用了定义在 新建 模态窗口中的 authorList
.