In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces ".NET 6 development of TodoList applications how to achieve data shaping". In daily operation, I believe that many people have doubts about how to achieve data shaping in .NET 6 development of TodoList applications. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of ".NET 6 development TodoList applications how to achieve data shaping". Next, please follow the editor to study!
Demand
Another type of requirement that is not very common in a query scenario is to specify the returned fields in the front-end request, so let's demonstrate data shaping (Data Shaping) on the last topic of search.
target
Realize the data shaping search request.
Principles and ideas
For data shaping, we need to define some interfaces and generic class implementations to complete the general functions, and then modify the corresponding query requests to achieve specific functions.
Implementation defines common interfaces and generic class implementations
IDataShaper.cs
Using System.Dynamic;namespace TodoList.Application.Common.Interfaces;public interface IDataShaper {IEnumerable ShapeData (IEnumerable entities, string fieldString); ExpandoObject ShapeData (T entity, string fieldString);}
And implement general functions:
DataShaper.cs
Using System.Dynamic;using System.Reflection;using TodoList.Application.Common.Interfaces;namespace TodoList.Application.Common;public class DataShaper: IDataShaper where T: class {public PropertyInfo [] Properties {get; set;} public DataShaper () {Properties = typeof (T) .GetProperties (BindingFlags.Public | BindingFlags.Instance);} public IEnumerable ShapeData (IEnumerable entities, string? FieldString) {var requiredProperties = GetRequiredProperties (fieldString); return GetData (entities, requiredProperties);} public ExpandoObject ShapeData (T entity, string? FieldString) {var requiredProperties = GetRequiredProperties (fieldString); return GetDataForEntity (entity, requiredProperties);} private IEnumerable GetRequiredProperties (string? FieldString) {var requiredProperties = new List (); if (! string.IsNullOrEmpty (fieldString)) {var fields = fieldString.Split (',', StringSplitOptions.RemoveEmptyEntries); foreach (var field in fields) {var property = Properties.FirstOrDefault (pi = > pi.Name.Equals (field.Trim (), StringComparison.InvariantCultureIgnoreCase)) If (property = = null) {continue;} requiredProperties.Add (property);} else {requiredProperties = Properties.ToList ();} return requiredProperties } private IEnumerable GetData (IEnumerable entities, IEnumerable requiredProperties) {return entities.Select (entity = > GetDataForEntity (entity, requiredProperties)). ToList ();} private ExpandoObject GetDataForEntity (T entity, IEnumerable requiredProperties) {var shapedObject = new ExpandoObject (); foreach (var property in requiredProperties) {var objectPropertyValue = property.GetValue (entity); shapedObject.TryAdd (property.Name, objectPropertyValue);} return shapedObject }} define extension methods
In order for our Handle method call chain to be applied directly, we add a DataShaperExtensions to Application/Extensions:
DataShaperExtensions.cs
Using System.Dynamic;using TodoList.Application.Common.Interfaces;namespace TodoList.Application.Common.Extensions;public static class DataShaperExtensions {public static IEnumerable ShapeData (this IEnumerable entities, IDataShaper shaper, string? FieldString) {return shaper.ShapeData (entities, fieldString);}}
Then add a method to the MappingExtensions static class we wrote earlier:
MappingExtensions.cs
/ / omit other... public static PaginatedList PaginatedListFromEnumerable (this IEnumerable entities, int pageNumber, int pageSize) {return PaginatedList.Create (entities, pageNumber, pageSize);} add dependency injection
Add dependency injection to the DependencyInjection.cs of Application:
DependencyInjection.cs
/ / omit other services.AddScoped (typeof (IDataShaper), typeof (DataShaper)); modify query request and Controller API
Based on the sorting implemented in the previous article, we add a field to indicate the data shaping field and modify the Handle method accordingly:
GetTodoItemsWithConditionQuery.cs
Using System.Dynamic;using AutoMapper;using AutoMapper.QueryableExtensions;using MediatR;using TodoList.Application.Common.Extensions;using TodoList.Application.Common.Interfaces;using TodoList.Application.Common.Mappings;using TodoList.Application.Common.Models;using TodoList.Application.TodoItems.Specs;using TodoList.Domain.Entities;using TodoList.Domain.Enums;namespace TodoList.Application.TodoItems.Queries.GetTodoItems;public class GetTodoItemsWithConditionQuery: IRequest {public Guid ListId {get; set;} public bool? Done {get; set;} public string? Title {get; set;} / / the front end indicates the field to be returned, public string? Fields {get; set;} public PriorityLevel? PriorityLevel {get; set;} public string? SortOrder {get; set;} = "title_asc"; public int PageNumber {get; set;} = 1; public int PageSize {get; set;} = 10;} public class GetTodoItemsWithConditionQueryHandler: IRequestHandler {private readonly IRepository _ repository; private readonly IMapper _ mapper; private readonly IDataShaper _ shaper; public GetTodoItemsWithConditionQueryHandler (IRepository repository, IMapper mapper, IDataShaper shaper) {_ repository = repository; _ mapper = mapper; _ shaper = shaper } public Task Handle (GetTodoItemsWithConditionQuery request, CancellationToken cancellationToken) {var spec = new TodoItemSpec (request) Return Task.FromResult (_ repository .GetAsQueryable (spec) .ProjectTo (_ mapper.ConfigurationProvider) .AsEnumerable () / / returns .ShapeData (_ shaper, request.Fields) .PaginatedListFromEnumerable (request.PageNumber, request.PageSize);}}
Modify Controller correspondingly:
TodoItemController.cs
[HttpGet] public async Task GetTodoItemsWithCondition ([FromQuery] GetTodoItemsWithConditionQuery query) {return ApiResponse.Success (await _ mediator.Send (query));} Verification
Start the Api project and execute the request for querying TodoItem:
Request
Response
Let's add the filtering and search mentioned earlier to the request:
Request
Response
At this point, the study of "how to achieve data shaping in the development of TodoList applications in .NET 6" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.