Building with Nano ASP.NET Boilerplate: Creating a New CRUD Service
Начало работы
In this walkthrough, we’ll create a new web application using the Nano CLI tool.
We will create a new Supplier entity, with an API controller и услуга. The Supplier entity will form a one-to-many relationship with the Продукт entity.
The Nano ASP.NET boilerplate is distributed as a NuGet package. For installation instructions, follow this guide. Once installed, you can use the project templates from the Developer PowerShell terminal.
Open a new terminal window and navigate to a folder to create the new project. In the terminal, use the dotnet nano command to create a new project:
dotnet new nano -n MyApp
You can replace the name attribute (-n) with the name of your project. By passing options for multi-tenancy (-m) или user interface (-ui) you can create projects with varying specifications. To learn more, check out the using the CLI tool guide.
Create a Supplier entity
We will start by creating a new entity called Supplier. This entity will be part of a one-to-many relationship with the Продукт entity.
The code is divided into layers, with the entities being part of the Domain layer.
Open the Domain layer and in the /Catalog folder, create a new entity class called Supplier. Supplier will have a Имя field and navigation property for Продукция. The navigation property will establish one side of the one-to-many relationship for Entity Framework. Inherit from the abstract class AuditableEntity.
общедоступный класс Supplier : AuditableEntity
{
общедоступный строка Имя { get; набор; }
общедоступный ICollection<Продукт> Продукция { get; набор; }
}Next we need to modify the Продукт entity to complete the one-to-many relationship for Entity Framework. Add a SupplierId field and Supplier navigation property.
общедоступный класс Продукт : AuditableEntity
{
общедоступный строка Имя { get; набор; }
общедоступный строка Описание { get; набор; }
общедоступный Supplier Supplier { get; набор; }
общедоступный Guid SupplierId { get; набор; }
}All entities should directly or indirectly inherit from abstract class BaseEntity, found in /Entities/Common.
AuditableEntity is an abstract class that inherits from TenantBaseEntity (or directly from BaseEntity in single-tenant deployments). AuditableEntity adds the CreatedBy, CreatedOn, LastModifiedBy, LastModifiedOn fields. By implementing the IAuditableEntity interface, the values of these fields are handled automatically whenever save changes occurs. Business entities usually inherit from AuditableEntity.
TenantBaseEntity inherits from the BaseEntity class and adds the Идентификатор арендатора field. By implementing the IMustHaveTenant interface, query filters in the ApplicationDbContext will isolate tenant data.
Откройте ApplicationDbContext в Infrastructure/Persistence/Contexts/ and create the DbSet для Supplier
общедоступный DbSet<Supplier> Suppliers { получить; набор; }Create a Migration
Next we need to create a migration to apply these schema changes to the database.
Open the Консоль диспетчера пакетов and set the default project to infrastructure. Use the following command to create a new migration:
add-migration -Context ApplicationDbContext -o Persistence/Migrations/AppDb App-SupplierEntity
If you deployed the project with single database multi-tenancy (-m singledb) or as single tenant (-m singletenant), then use this command:
add-migration -Context ApplicationDbContext -o Persistence/Migrations SupplierEntity
Run the application to apply the migrations or use the обновить базу данных command.
В ApplicationDbContext you can find a quick reference for all the миграция commands in the code comments.
Create the Supplier Service
Next we’ll use the Nano CLI to create a service for the new entity.
В Developer PowerShell, change directory to MyApp.Application\Services and then run the following command:
dotnet new nano-service -s Supplier -p Suppliers -ap MyApp
If building with Razor pages, use this command:
dotnet new nano-service -s Supplier -p Suppliers -ap MyApp -ui razor
All the code for a new service feature will be created within the SupplierService folder:

Passing the -ui razor option will scaffold slightly different code for the pagination method, otherwise it’s the same
The new service contains all the methods for basic CRUD operations. Here is the scaffolded ISupplierService code for reference:
общедоступный интерфейс ISupplierService : ITransientService
{
Задача<Response<IEnumerable<SupplierDTO>>> GetSuppliersAsync(строка keyword = "");
Задача<PaginatedResponse<SupplierDTO>> GetSuppliersPaginatedAsync(SupplierTableFilter filter);
Задача<Response<SupplierDTO>> GetSupplierAsync(Guid id);
Задача<Response<Guid>> CreateSupplierAsync(CreateSupplierRequest request);
Задача<Response<Guid>> UpdateSupplierAsync(UpdateSupplierRequest request, Guid id);
Задача<Response<Guid>> DeleteSupplierAsync(Guid id);
}This service will register as a transient service since it implements the ITransientService interface. To register as scoped, change to IScopedService. You can read more about services in the application services guide.
Customize the Supplier DTOs
DTO для supplier service can be found within Application/Services/SupplierService/DTOs. All DTOs implement the IDto marker interface.
Since the dotnet CLI tool is not aware of entities and their properties, a scaffolded DTO from dotnet new nano-service will only contain an Идентификатор и Имя property. Customize your entities as you need to.
In this case, the SupplierDTO should also contain a list of Продукция. Add a new list of ProductDTO List to the SupplierDTO:
общедоступный класс SupplierDTO : IDto
{
общедоступный Guid Id { get; набор; }
общедоступный строка Имя { get; набор; }
общедоступный IList<ProductDTO> Продукция { get; набор; }
}Creating a new service with the dotnet new nano-service command also creates DTOs for Создать и Update requests. The generated DTO contains a Имя field with validation and should be modified per your needs in regards to the properties in your entity.
общедоступный класс CreateSupplierRequest : IDto
{
общедоступный строка Имя { get; набор; }
}
общедоступный класс CreateSupplierValidator : AbstractValidator<CreateSupplierRequest>
{
общедоступный CreateSupplierValidator()
{
RuleFor(x => x.Имя).NotEmpty();
}
}Update the Product DTOs
Because we now have a one-to-many relationship between Supplier и Продукт, creating and updating Продукция requires a supplier ID. Navigate to Application/Services/ProductService/DTOs and add a SupplierId property for the Update и Создать product requests.
общедоступный класс CreateProductRequest : IDto
{
общедоступный строка Имя { get; набор; }
общедоступный строка Описание { get; набор; }
общедоступный Guid SupplierId { get; набор; }
}
общедоступный класс CreateProductValidator : AbstractValidator<CreateProductRequest>
{
общедоступный CreateProductValidator()
{
_ = RuleFor(x => x.Имя).NotEmpty();
_ = RuleFor(x => x.Описание).NotEmpty();
_ = RuleFor(x => x.SupplierId).NotEmpty();
}
}On the ProductDTO, add a GUID SupplierId and a SupplierName string property. In the next step, we will configure Automapper to populate the SupplierName whenever mapping occurs.
общедоступный класс ProductDTO : IDto
{
общедоступный Guid Id { get; набор; }
общедоступный строка? Имя { get; набор; }
общедоступный строка? Описание { get; набор; }
общедоступный DateTime CreatedOn { get; набор; }
общедоступный строка SupplierName { get; набор; }
общедоступный Guid SupplierId { get; набор; }
}Configure Automapping
Next we need to set up mapping profiles for the new DTOs
В Infrastructure/Mapper/MappingProfiles add the following configurations for supplier:
// supplier mappings...
_ = CreateMap<Supplier, SupplierDTO>();
_ = CreateMap<CreateSupplierRequest, Supplier>();
_ = CreateMap<UpdateSupplierRequest, Supplier>();This will ensure that Automapper knows how to map a Supplier entity to a SupplierDTO и Создать / Update requests to a Supplier entity.
Modify the product mappings so that when going from Продукт в ProductDTO, the SupplierName field is mapped from the Supplier entity.
// product mappings
_ = CreateMap<Продукт, ProductDTO>().ForMember(x => x.SupplierName, o => o.MapFrom(s => s.Supplier.Имя));
_ = CreateMap<CreateProductRequest, Продукт>();
_ = CreateMap<UpdateProductRequest, Продукт>();With that bit of manual labor out of the way, we can wrap things up in the next step by creating an API controller.
Create the Supplier Controller
We’ll use the Nano CLI again to create an API controller.
В Developer PowerShell, change directory to MyApp.WebApi\Controllers and run the following command:
dotnet new nano-controller -s Supplier -p Suppliers -ap MyApp
If building with Razor pages, change directory to MyApp.RazorApp\Controllers use this command:
dotnet new nano-controller -s Supplier -p Suppliers -ap MyApp -ui razor
This will create a new controller with endpoints for the CRUD methods provided in the SupplierService we scaffolded earlier.
Testing with Postman
Now we can test with Почтальон. Create a new folder for Suppliers with a Сообщение request called create-supplier. Create a few suppliers; remember to first obtain a token.

Create a new Получить request called get-suppliers-full-list and retrieve the list of suppliers. Copy one of the supplier IDs so that we can use it to create a product in the next step.

В Продукция folder, modify the create-product request body to have a SupplierId field. Create a new товар for one of the suppliers

Now when you retrieve a list of suppliers, an array of продукты will be returned.

Returning a list of продукты works as well, with Automapper taking care of the supplier name field for us

With the Nano Boilerplate CLI tool, creating a new app feature is easy. The bulk of the code can be generated using the dotnet new commands, allowing you to focus on the unique aspects of your project.
That concludes the walkthrough, hopefully now you have a better understanding of how to build API endpoints with the Nano ASP.NET boilerplate!