This project implements a design pattern known as the Layered Architecture Pattern. This pattern that implements controllers, services, repositories, data, model, and logic in different layers. The Layered Architecture Pattern organizes an application into logical layers, where each layer has a specific responsibility and communicates with other layers in an orderly manner.
Here is how the layers are structured in the project:
-
Common.WebApi:
- Responsibility: Manages the user interface and user interaction.
- Typical Components: Controllers, mappings, and DTOs.
-
Common.Business:
- Responsibility: Coordinates application logic and business rules.
- Typical Components: Application logic, service implementations, and generic repositories from the Core layer.
-
Common.Core:
- Responsibility: Provides generic data context, base services and repositories that **implement typical CRUD operations, filtering, sorting and pagination.
- Typical Components: Services, repositories, data context, classes for dynamic lambda expressions generation.
-
Common.Domain:
- Responsibility: Contains the ORM models, database context implementation, and migrations.
- Typical Components: ORM models, database context implementation, and migrations.
-
Common.Tests:
- Responsibility: Ensures code quality and functionality through testing.
- Typical Components: Unit tests.
This pattern promotes the separation of concerns, facilitates maintenance and scalability of the system, and improves code reuse.
Now, imagine you have to add more than 20 new entities to your application with controller and service CRUD operations, search by different field names, sorting and paging data, let's take for example one of them: Clients. To achieve this, with this architecture, you must only implement:
An empty Controller: GenericControllerBase will implement all CRUD operations (post, put, patch, get, delete, filter (GetAll filtered), sorting and pagination) for you!
[Route("api/v1/[controller]")]
public class ClientController : GenericControllerBase<Client, ClientRequestDto, ClientResponseDto, ClientQueryFilter, ClientRequestDtoValidator>
{
public ClientController(
ILogger<ClientController> logger,
IBaseService<Client, int> clientService) : base(logger, clientService)
{
}
}A Repository: Same thing, you have all necessary logic in BaseRepository
public class ClientRepository : BaseRepository<Client>
{
public ClientRepository(AppDbContext ctx) : base(ctx)
{
}
}A DTO to send back to client
public class ClientResponseDto : IEntity
{
public int Id { get; set; }
public string? Name { get; set; }
public string? Email { get; set; }
...
}An Automapper mapping class
public class ClientMappingProfile : Profile
{
public MappingProfile()
{
CreateMap<Client, ClientRequestDto>().ReverseMap();
CreateMap<Client, ClientResponseDto>().ReverseMap();
}
}You decide which entity fields you want to filter by, just declaring the same entity field names in the DTO your controller is expecting:
public class ClientQueryFilter : BaseRequest
{
public int? Id { get; set; }
public string? Name { get; set; }
public DateTime? BirthDate { get; set; }
}If you need advanced filtering, such as something like this:
DbContext.Clients.Where(c => c.Id >= 10 && c.Id <= 30);
DbContext.Clients.Where(c => listIDs.Contains(c.Id));
DbContext.Clients.Where(c => c.DateStart >= DateTime.Now && c.DateEnd <= DateTime.Now.AddMinutes(5));
DbContext.Clients.Where(c => c.Summary.Contains("some text"));You can just declare a Queryfilter class and declare some fields with predefined prefixes (Min, Max, GreaterThan, LessThan, List, Contains) followed by the entity field name you want to filter by:
public class ClientQueryFilter : ClientDynamicFieldsQueryFilter
{
public int? Id { get; set; }
public string? Name { get; set; }
...
}
public class ClientDynamicFieldsQueryFilter : BaseRequest, IDynamicQueryFilter
{
// List of IDs
public List<int>? ListId { get; set; }
// >=, <= numbers
public int? LessThanOrEqualId { get; set; }
public int? GreaterThanOrEqualId { get; set; }
public int? GreaterThanId { get; set; }
public int? LessThanId { get; set; }
// Contains name, List names
public string? ContainsName { get; set; }
public string[]? ListName { get; set; }
// >=, <= dates
public DateTime? GreaterThanOrEqualBirthDate { get; set; }
public DateTime? LessThanOrEqualBirthDate { get; set; }
public DateTime? GreaterThanBirthDate { get; set; }
public DateTime? LessThanBirthDate { get; set; }
}Note: the prefixes can be customised in
appsettings.json(see below). If you need a property with a completely different name, use the[FilterOperator]attribute instead (see below), which always takes precedence over the prefix convention.
The prefix names are read from the DynamicFiltersConfiguration section of appsettings.json at startup. The values below are the defaults:
"DynamicFiltersConfiguration": {
"ListFieldName": "List",
"ContainsFieldName": "Contains",
"GreaterThanOrEqualFieldName": "GreaterThanOrEqual",
"GreaterThanFieldName": "GreaterThan",
"LessThanOrEqualFieldName": "LessThanOrEqual",
"LessThanFieldName": "LessThan"
}You can override any prefix without touching the code. For example, to use From / To instead of GreaterThanOrEqual / LessThanOrEqual:
"DynamicFiltersConfiguration": {
"GreaterThanOrEqualFieldName": "From",
"LessThanOrEqualFieldName": "To"
}public class ClientDynamicFieldsQueryFilter : BaseRequest, IDynamicQueryFilter
{
public DateTime? FromBirthDate { get; set; } // maps to entity.BirthDate >= value
public DateTime? ToBirthDate { get; set; } // maps to entity.BirthDate <= value
}By default the engine uses the prefix convention described above: it inspects the property name to decide which kind of expression to build.
If you prefer freely named properties (e.g. you want BornAfter instead of GreaterThanOrEqualBirthDate), decorate the property with [FilterOperator]:
public class ClientSearchFilter : BaseRequest, IDynamicQueryFilter
{
// No prefix needed — the operation is declared explicitly
[FilterOperator(FilterOperator.Contains)]
public string? NameFragment { get; set; } // matches Name.Contains(value)
[FilterOperator(FilterOperator.GreaterThanOrEqual, EntityProperty = nameof(Client.BirthDate))]
public DateTime? BornAfter { get; set; } // maps to entity.BirthDate >= value
[FilterOperator(FilterOperator.LessThanOrEqual, EntityProperty = nameof(Client.BirthDate))]
public DateTime? BornBefore { get; set; } // maps to entity.BirthDate <= value
[FilterOperator(FilterOperator.List, EntityProperty = nameof(Client.Id))]
public List<int>? Ids { get; set; } // translates to SQL IN (...)
}The EntityProperty parameter is required only when the filter property name differs from the entity property name.
When it is omitted the engine matches by name directly ([FilterOperator(FilterOperator.Equals)] public string? Name → entity.Name == value).
By default every non-null field in a query-filter is combined with AND. To switch a filter class to OR (at least one condition must match), override the LogicOperator property from IDynamicQueryFilter:
public class ClientOrFilter : BaseRequest, IDynamicQueryFilter
{
// All non-null fields will be combined with OR
public FilterLogicOperator? LogicOperator => FilterLogicOperator.Or;
public string? Name { get; set; }
public string? Email { get; set; }
}// Returns clients whose Name == "Alice" OR Email == "alice@example.com"
var filter = new ClientOrFilter { Name = "Alice", Email = "alice@example.com" };
var results = await clientService.GetAllAsync(filter);This is equivalent to:
dbContext.Clients.Where(c => c.Name == "Alice" || c.Email == "alice@example.com")Note:
LogicOperatorapplies to all fields in the filter class. If you need mixed AND/OR logic across different groups of fields, split them into separate filter classes and compose the results in your service or repository layer.
The main class that generates the magic is DynamicExpression in method SetPredicate(TQueryFilter filter)
You can have a look at unit tests starting with Get_ByDynamicFilter... to se how it works :)
-
Centralization of Common Logic:
- BaseService and BaseRepository encapsulates and centralizes common logic for CRUD operations (Create, Read, Update, Delete). This avoids code duplication in each specific domain service. If a case arises that cannot be implemented generically, any functionality can be inherited and overridden.
-
Decoupling of DTOs and Entities:
- Effective decoupling of DTOs and entities is achieved, ensuring that the presentation and business layers remain independent and manageable.
-
Use of Generic Types and Type Abstraction:
- By using generic types, BaseService and BaseRepository can handle any type of entity without needing to know specific details about the entity. This makes BaseService and BaseRepository extremely flexible and reusable.
-
Automatic Mapping with AutoMapper:
- Automatic mapping with AutoMapper through the projection (ProjectTo()) of data directly into DTOs in a single atomic operation improves efficiency and performance when handling large volumes of data.
-
Generation of Dynamic Lambda Expressions:
- The generation of dynamic Lambda expressions in IQueryable directly from DTOs allows:
- Use of special fields (GreaterThan, LessThan, GreaterThanOrEqual, LessThanOrEqual, Contains, List) that automate the generation of simple queries, reducing the estimated development time.
- Automation of sorting and pagination of records.
- The generation of dynamic Lambda expressions in IQueryable directly from DTOs allows:
-
Decoupling Data layer from Model/Domain:
- Using a Base DbContext to manage Entity migrations and IEntityTypeConfiguration for better EF Code First management
-
Simple UI:
- This project implements Swagger, so you can test all application functionality.
Runtime This project requires .NET 9 or later.
SQL Server
This software uses SQL Server database, so to work properly you need to install SQL Server and update the ConnectionString in appsettings.json.
Code Coverage reports In order to generate code coverage reports properly with coverlete tool you need to install reportgenerator separately:
dotnet tool install -g dotnet-reportgenerator-globaltool- Open Solution and build it.
- Run database migrations, this will create the database and needed data:
dotnet ef database update --project "./Common.Domain/Common.Domain.csproj" --startup-project "./Common.WebApi/Common.WebApi.csproj"This example ilustrates how some entities can be managed (CRUD), filtered, sorted and paginated with query filters and transform/return DTOs automatically.
Entities: Client, Photographer, Session, Location
Description: Allows photographers to manage their sessions with clients. Users can register information about the sessions (date, time, location, type of session), client data, and assigned photographers. Notes or comments about each session can also be added.
You can extend very easy the implementation of new filters extending from DynamicExpression<T, TQueryFilter> (i.e. see ListDynamicExpression or RangeDynamicExpression implementations)
A feature that would be nice to have is for example filtering aggregate queries (grouping) and harnessing the existing filtering, sorting and paging functionality
All the source code in this project is 100% my own work, and it is the result of several years of experience in software development. A very important part of this involves not only coding but reading documentation of all the frameworks and technologies that are part of this project, as well as many hours of effort and dedication that have helped me refine and choose the best programming techniques. For any questions regarding this source code, you can ask me or create a Pull Request :).
Thank you and Happy Coding! :)