Web Application Development Tutorial - Part 10: Book to Author Relation
About This Tutorial
In this tutorial series, you will build an ABP based web application named Acme.BookStore
. This application is used to manage a list of books and their authors. It is developed using the following technologies:
- Entity Framework Core as the ORM provider.
- MVC / Razor Pages as the UI Framework.
This tutorial is organized as the following parts;
- Part 1: Creating the server side
- Part 2: The book list page
- Part 3: Creating, updating and deleting books
- Part 4: Integration tests
- Part 5: Authorization
- Part 6: Authors: Domain layer
- Part 7: Authors: Database Integration
- Part 8: Authors: Application Layer
- Part 9: Authors: User Interface
- Part 10: Book to Author Relation (this part)
Download the Source Code
This tutorial has multiple versions based on your UI and Database preferences. We've prepared a few combinations of the source code to be downloaded:
If you encounter the "filename too long" or "unzip error" on Windows, it's probably related to the Windows maximum file path limitation. Windows has a maximum file path limitation of 250 characters. To solve this, enable the long path option in Windows 10.
If you face long path errors related to Git, try the following command to enable long paths in Windows. See https://github.com/msysgit/msysgit/wiki/Git-cannot-create-a-file-or-directory-with-a-long-path
git config --system core.longpaths true
Introduction
We have created Book
and Author
functionalities for the book store application. However, currently there is no relation between these entities.
In this tutorial, we will establish a 1 to N relation between the Author
and the Book
entities.
Add Relation to The Book Entity
Open the Books/Book.cs
in the Acme.BookStore.Domain
project and add the following property to the Book
entity:
In this tutorial, we preferred to not add a navigation property to the
Author
entity from theBook
class (likepublic Author Author { get; set; }
). This is due to follow the DDD best practices (rule: refer to other aggregates only by id). However, you can add such a navigation property and configure it for the EF Core. In this way, you don't need to write join queries while getting books with their authors (like we will done below) which makes your application code simpler.
Database & Data Migration
Added a new, required AuthorId
property to the Book
entity. But, what about the existing books on the database? They currently don't have AuthorId
s and this will be a problem when we try to run the application.
This is a typical migration problem and the decision depends on your case;
- If you haven't published your application to the production yet, you can just delete existing books in the database, or you can even delete the entire database in your development environment.
- You can update the existing data programmatically on data migration or seed phase.
- You can manually handle it on the database.
We prefer to delete the database (you can run the Drop-Database
in the Package Manager Console) since this is just an example project and data loss is not important. Since this topic is not related to the ABP Framework, we don't go deeper for all the scenarios.
Update the EF Core Mapping
Locate to OnModelCreating
method in the BookStoreDbContext
class that under the EntityFrameworkCore
folder of the Acme.BookStore.EntityFrameworkCore
project and change the builder.Entity<Book>
part as shown below:
Add New EF Core Migration
The startup solution is configured to use Entity Framework Core Code First Migrations. Since we've changed the database mapping configuration, we should create a new migration and apply changes to the database.
Open a command-line terminal in the directory of the Acme.BookStore.EntityFrameworkCore
project and type the following command:
This should create a new migration class with the following code in its Up
method:
- Adds an
AuthorId
field to theAppBooks
table. - Creates an index on the
AuthorId
field. - Declares the foreign key to the
AppAuthors
table.
If you are using Visual Studio, you may want to use
Add-Migration Added_AuthorId_To_Book -c BookStoreDbContext
andUpdate-Database -Context BookStoreDbContext
commands in the Package Manager Console (PMC). In this case, ensure thatAcme.BookStore.Web
is the startup project andAcme.BookStore.EntityFrameworkCore
is the Default Project in PMC.
Change the Data Seeder
Since the AuthorId
is a required property of the Book
entity, current data seeder code can not work. Open the BookStoreDataSeederContributor
in the Acme.BookStore.Domain
project and change as the following:
The only change is that we set the AuthorId
properties of the Book
entities.
Delete existing books or delete the database before executing the
DbMigrator
. See the Database & Data Migration section above for more info.
You can now run the .DbMigrator
console application to migrate the database schema and seed the initial data.
Application Layer
We will change the BookAppService
to support the Author relation.
Data Transfer Objects
Let's begin from the DTOs.
BookDto
Open the BookDto
class in the Books
folder of the Acme.BookStore.Application.Contracts
project and add the following properties:
The final BookDto
class should be following:
CreateUpdateBookDto
Open the CreateUpdateBookDto
class in the Books
folder of the Acme.BookStore.Application.Contracts
project and add an AuthorId
property as shown:
AuthorLookupDto
Create a new class, AuthorLookupDto
, inside the Books
folder of the Acme.BookStore.Application.Contracts
project:
This will be used in a new method that will be added to the IBookAppService
.
IBookAppService
Open the IBookAppService
interface in the Books
folder of the Acme.BookStore.Application.Contracts
project and add a new method, named GetAuthorLookupAsync
, as shown below:
This new method will be used from the UI to get a list of authors and fill a dropdown list to select the author of a book.
BookAppService
Open the BookAppService
class in the Books
folder of the Acme.BookStore.Application
project and replace the file content with the following code:
Let's see the changes we've done:
- Added
[Authorize(BookStorePermissions.Books.Default)]
to authorize the methods we've newly added/overrode (remember, authorize attribute is valid for all the methods of the class when it is declared for a class). - Injected
IAuthorRepository
to query from the authors. - Overrode the
GetAsync
method of the baseCrudAppService
, which returns a singleBookDto
object with the givenid
.- Used a simple LINQ expression to join books and authors and query them together for the given book id.
- Used
AsyncExecuter.FirstOrDefaultAsync(...)
to execute the query and get a result. It is a way to use asynchronous LINQ extensions without depending on the database provider API. Check the repository documentation to understand why we've used it. - Throws an
EntityNotFoundException
which results anHTTP 404
(not found) result if requested book was not present in the database. - Finally, created a
BookDto
object using theObjectMapper
, then assigning theAuthorName
manually.
- Overrode the
GetListAsync
method of the baseCrudAppService
, which returns a list of books. The logic is similar to the previous method, so you can easily understand the code. - Created a new method:
GetAuthorLookupAsync
. This simple gets all the authors. The UI uses this method to fill a dropdown list and select and author while creating/editing books.
Object to Object Mapping Configuration
Introduced the AuthorLookupDto
class and used object mapping inside the GetAuthorLookupAsync
method. So, we need to add a new mapping definition inside the BookStoreApplicationAutoMapperProfile.cs
file of the Acme.BookStore.Application
project:
Unit Tests
Some of the unit tests will fail since we made some changed on the AuthorAppService
. Open the BookAppService_Tests
in the Books
folder of the Acme.BookStore.Application.Tests
project and change the content as the following:
- Changed the assertion condition in the
Should_Get_List_Of_Books
fromb => b.Name == "1984"
tob => b.Name == "1984" && b.AuthorName == "George Orwell"
to check if the author name was filled. - Changed the
Should_Create_A_Valid_Book
method to set theAuthorId
while creating a new book, since it is required anymore.
The User Interface
The Book List
Book list page change is trivial. Open the Pages/Books/Index.js
in the Acme.BookStore.Web
project and add the following column definition between the name
and type
columns:
When you run the application, you can see the Author column on the table:
Create Modal
Open the Pages/Books/CreateModal.cshtml.cs
in the Acme.BookStore.Web
project and change the file content as shown below:
- Changed type of the
Book
property fromCreateUpdateBookDto
to the newCreateBookViewModel
class defined in this file. The main motivation of this change to customize the model class based on the User Interface (UI) requirements. We didn't want to use UI-related[SelectItems(nameof(Authors))]
and[DisplayName("Author")]
attributes inside theCreateUpdateBookDto
class. - Added
Authors
property that is filled inside theOnGetAsync
method using theIBookAppService.GetAuthorLookupAsync
method defined before. - Changed the
OnPostAsync
method to mapCreateBookViewModel
object to aCreateUpdateBookDto
object sinceIBookAppService.CreateAsync
expects a parameter of this type.
Edit Modal
Open the Pages/Books/EditModal.cshtml.cs
in the Acme.BookStore.Web
project and change the file content as shown below:
- Changed type of the
Book
property fromCreateUpdateBookDto
to the newEditBookViewModel
class defined in this file, just like done before for the create modal above. - Moved the
Id
property inside the newEditBookViewModel
class. - Added
Authors
property that is filled inside theOnGetAsync
method using theIBookAppService.GetAuthorLookupAsync
method. - Changed the
OnPostAsync
method to mapEditBookViewModel
object to aCreateUpdateBookDto
object sinceIBookAppService.UpdateAsync
expects a parameter of this type.
These changes require a small change in the EditModal.cshtml
. Remove the <abp-input asp-for="Id" />
tag since we no longer need to it (since moved it to the EditBookViewModel
). The final content of the EditModal.cshtml
should be following:
Object to Object Mapping Configuration
The changes above requires to define some object to object mappings. Open the BookStoreWebAutoMapperProfile.cs
in the Acme.BookStore.Web
project and add the following mapping definitions inside the constructor:
You can run the application and try to create a new book or update an existing book. You will see a drop down list on the create/update form to select the author of the book: