Modelo Nano ASP.NET para SaaS
Credenciais de administrador (todos os locatários): admin@email.com / Password123!
Os dados de amostra são reiniciados a cada hora

Building with Nano ASP.NET Boilerplate: Creating a New CRUD Service

Ryan Lewis
abril 21, 2024

In this walkthrough, we’ll create a new web application using the Nano CLI tool.

We will create a new Fornecedor entity, with an Controlador de API e serviço. O Fornecedor entity will form a one-to-many relationship with the Produto 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) ou user interface (-ui) you can create projects with varying specifications. To learn more, check out the using the CLI tool guide.

We will start by creating a new entity called Fornecedor. This entity will be part of a um-para-muitos relationship with the Produto entity.

The code is divided into layers, with the entities being part of the Domínio layer.

Open the Domínio layer and in the /Catalog folder, create a new entity class called Fornecedor. Fornecedor terá um Nome field and navigation property for Produtos. The navigation property will establish one side of the one-to-many relationship for Entity Framework. Inherit from the abstract class AuditableEntity.

    público classe Fornecedor : AuditableEntity
    {
        público string Nome { obter; definir; }

        público ICollection<Produto> Produtos { obter; definir; }
    }

Next we need to modify the Produto entity to complete the one-to-many relationship for Entity Framework. Add a ID do fornecedor field and Fornecedor navigation property.

    público classe Produto : AuditableEntity 
    {
        público string Nome { obter; definir; }
        público string Descrição { obter; definir; }
        público Fornecedor Fornecedor { obter; definir; }
        público Guid SupplierId { obter; definir; }
    }

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 ID do locatário field. By implementing the IMustHaveTenant interface, query filters in the ApplicationDbContext will isolate tenant data.

Abra ApplicationDbContext em Infrastructure/Persistence/Contexts/ and create the DbSet para Fornecedor

público DbSet<Fornecedor> Fornecedores { obter; conjunto; }

Next we need to create a migration to apply these schema changes to the database.

Open the Console do Gerenciador de Pacotes and set the default project to infraestrutura. 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 atualizar-banco-de-dados comando.

Em ApplicationDbContext you can find a quick reference for all the migração commands in the code comments.

Next we’ll use the Nano CLI to create a service for the new entity.

No 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:

    público interface ISupplierService : ITransientService
    {
        Tarefa<Response<IEnumerable<Fornecedor DTO>>> GetSuppliersAsync(string keyword = "");
        Tarefa<PaginatedResponse<Fornecedor DTO>> GetSuppliersPaginatedAsync(SupplierTableFilter filter);
        Tarefa<Response<Fornecedor DTO>> GetSupplierAsync(Guid id);
        Tarefa<Response<Guid>> CreateSupplierAsync(Solicitação CreateSupplierRequest);
        Tarefa<Response<Guid>> UpdateSupplierAsync(UpdateSupplierRequest request, Guid id);
        Tarefa<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.

DTOs para o 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 Id e Nome property. Customize your entities as you need to.

In this case, the Fornecedor DTO should also contain a list of Produtos. Add a new list of ProductDTO List to the Fornecedor DTO:

    público classe Fornecedor DTO : IDto
    {
        público Guid Id { obter; definir; }
        público string Nome { obter; definir; }
        público IList<ProductDTO> Produtos { obter; definir; }
    }

Creating a new service with the dotnet new nano-service command also creates DTOs for Criar e Atualização requests. The generated DTO contains a Nome field with validation and should be modified per your needs in regards to the properties in your entity.

    público classe CriarSolicitaçãoDeFornecedor : IDto
    {
        público string Nome { obter; definir; }
    }
    público classe CreateSupplierValidator : AbstractValidator<CriarSolicitaçãoDeFornecedor>
    {
        público CreateSupplierValidator()
        {
            RuleFor(x => x.Nome).NotEmpty();
        }
    }

Because we now have a um-para-muitos relationship between Fornecedor e Produto, creating and updating Produtos requires a supplier ID. Navigate to Application/Services/ProductService/DTOs and add a ID do fornecedor property for the Atualização e Criar product requests.

público classe Solicitação de Criação de Produto : IDto
{
    público string Nome { obter; definir; }
    público string Descrição { obter; definir; }
    público Guid SupplierId { obter; definir; }

}

público classe CreateProductValidator : AbstractValidator<Solicitação de Criação de Produto>
{
    público CreateProductValidator()
    {
        _ = RuleFor(x => x.Nome).NotEmpty();
        _ = RuleFor(x => x.Descrição).NotEmpty();
        _ = RuleFor(x => x.ID do fornecedor).NotEmpty();

    }
}

On the ProductDTO, add a GUID ID do fornecedor e um Nome do fornecedor string property. In the next step, we will configure Automapper to populate the Nome do fornecedor whenever mapping occurs.

    público classe ProductDTO : IDto
    {
        público Guid Id { obter; definir; }
        público string? Nome { obter; definir; }
        público string? Descrição { obter; definir; }
        público DateTime CreatedOn { obter; definir; }
        público string Nome do fornecedor { obter; definir; }
        público Guid SupplierId { obter; definir; }
    }

Next we need to set up mapping profiles for the new DTOs

Em Infrastructure/Mapper/MappingProfiles add the following configurations for supplier:

            // supplier mappings...
            _ = CreateMap<Fornecedor, Fornecedor DTO>();
            _ = CreateMap<CriarSolicitaçãoDeFornecedor, Fornecedor>();
            _ = CreateMap<AtualizarSolicitaçãoDeFornecedor, Fornecedor>();

This will ensure that Automapper knows how to map a Fornecedor entity to a Fornecedor DTO e o Criar / Atualização requests to a Fornecedor entity.

Modify the product mappings so that when going from Produto para ProductDTO, o Nome do fornecedor field is mapped from the Fornecedor entity.

            // product mappings
            _ = CreateMap<Produto, ProductDTO>().ForMember(x => x.Nome do fornecedor, o => o.MapFrom(s => s.Fornecedor.Nome));
            _ = CreateMap<Solicitação de Criação de Produto, Produto>();
            _ = CreateMap<Solicitação de Atualização de Produto, Produto>();

With that bit of manual labor out of the way, we can wrap things up in the next step by creating an API controller.

We’ll use the Nano CLI again to create an API controller.

No 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-controlador -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.

Now we can test with Carteiro. Create a new folder for Fornecedores com um Postagem request called create-supplier. Create a few suppliers; remember to first obtain a token.

Test API Post

Create a new Obter 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.

Test API Get

No Produtos folder, modify the create-product request body to have a ID do fornecedor field. Create a new produto for one of the suppliers

Test API Create Product

Now when you retrieve a list of fornecedores, an array of produtos will be returned.

Test API Get Listing

Returning a list of produtos works as well, with Automapper taking care of the supplier name field for us

Test API Get List of Products

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!

Precisa de um modelo ASP.NET para desenvolver seu próximo MVP?
Confira o projeto modelo Nano ASP.NET para SaaS multilocatário e economize semanas ou meses de tempo de desenvolvimento.
Saiba mais