最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

.NET 6開發(fā)TodoList應(yīng)用之實現(xiàn)數(shù)據(jù)塑形

 更新時間:2022年01月05日 09:05:31   作者:CODE4NOTHING  
在查詢的場景中,還有一類需求不是很常見,就是在前端請求中指定返回的字段。所以這篇文章主要介紹了.NET 6如何實現(xiàn)數(shù)據(jù)塑形,需要的可以參考一下

需求

在查詢的場景中,還有一類需求不是很常見,就是在前端請求中指定返回的字段,所以關(guān)于搜索的最后一個主題我們就來演示一下關(guān)于數(shù)據(jù)塑形(Data Shaping)。

目標(biāo)

實現(xiàn)數(shù)據(jù)塑形搜索請求。

原理與思路

對于數(shù)據(jù)塑形來說,我們需要定義一些接口和泛型類實現(xiàn)來完成通用的功能,然后修改對應(yīng)的查詢請求,實現(xiàn)具體的功能。

實現(xiàn)

定義通用接口和泛型類實現(xiàn)

IDataShaper.cs

using System.Dynamic;

namespace TodoList.Application.Common.Interfaces;

public interface IDataShaper<T>
{
    IEnumerable<ExpandoObject> ShapeData(IEnumerable<T> entities, string fieldString);
    ExpandoObject ShapeData(T entity, string fieldString);
}

并實現(xiàn)通用的功能:

DataShaper.cs

using System.Dynamic;
using System.Reflection;
using TodoList.Application.Common.Interfaces;

namespace TodoList.Application.Common;

public class DataShaper<T> : IDataShaper<T> where T : class
{
    public PropertyInfo[] Properties { get; set; }

    public DataShaper()
    {
        Properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
    }

    public IEnumerable<ExpandoObject> ShapeData(IEnumerable<T> 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<PropertyInfo> GetRequiredProperties(string? fieldString)
    {
        var requiredProperties = new List<PropertyInfo>();

        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<ExpandoObject> GetData(IEnumerable<T> entities, IEnumerable<PropertyInfo> requiredProperties)
    {
        return entities.Select(entity => GetDataForEntity(entity, requiredProperties)).ToList();
    }

    private ExpandoObject GetDataForEntity(T entity, IEnumerable<PropertyInfo> requiredProperties)
    {
        var shapedObject = new ExpandoObject();
        foreach (var property in requiredProperties)
        {
            var objectPropertyValue = property.GetValue(entity);
            shapedObject.TryAdd(property.Name, objectPropertyValue);
        }

        return shapedObject;
    }
}

定義擴展方法

為了使我們的Handle方法調(diào)用鏈能夠直接應(yīng)用,我們在Application/Extensions中新增一個DataShaperExtensions:

DataShaperExtensions.cs

using System.Dynamic;
using TodoList.Application.Common.Interfaces;

namespace TodoList.Application.Common.Extensions;

public static class DataShaperExtensions
{
    public static IEnumerable<ExpandoObject> ShapeData<T>(this IEnumerable<T> entities, IDataShaper<T> shaper, string? fieldString)
    {
        return shaper.ShapeData(entities, fieldString);
    }
}

然后再對我們之前寫的MappingExtensions靜態(tài)類中添加一個方法:

MappingExtensions.cs

// 省略其他...
public static PaginatedList<TDestination> PaginatedListFromEnumerable<TDestination>(this IEnumerable<TDestination> entities, int pageNumber, int pageSize)
{
    return PaginatedList<TDestination>.Create(entities, pageNumber, pageSize);   
}

添加依賴注入

在Application的DependencyInjection.cs中添加依賴注入:

DependencyInjection.cs

// 省略其他
services.AddScoped(typeof(IDataShaper<>), typeof(DataShaper<>));

修改查詢請求和Controller接口

我們在上一篇文章實現(xiàn)排序的基礎(chǔ)上增加一個字段用于指明數(shù)據(jù)塑形字段并對應(yīng)修改Handle方法:

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<PaginatedList<ExpandoObject>>
{
    public Guid ListId { get; set; }
    public bool? Done { get; set; }
    public string? Title { get; set; }
    // 前端指明需要返回的字段
    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<GetTodoItemsWithConditionQuery, PaginatedList<ExpandoObject>>
{
    private readonly IRepository<TodoItem> _repository;
    private readonly IMapper _mapper;
    private readonly IDataShaper<TodoItemDto> _shaper;

    public GetTodoItemsWithConditionQueryHandler(IRepository<TodoItem> repository, IMapper mapper, IDataShaper<TodoItemDto> shaper)
    {
        _repository = repository;
        _mapper = mapper;
        _shaper = shaper;
    }

    public Task<PaginatedList<ExpandoObject>> Handle(GetTodoItemsWithConditionQuery request, CancellationToken cancellationToken)
    {
        var spec = new TodoItemSpec(request);
        return Task.FromResult(
            _repository
                .GetAsQueryable(spec)
                .ProjectTo<TodoItemDto>(_mapper.ConfigurationProvider)
                .AsEnumerable()
                // 進行數(shù)據(jù)塑形和分頁返回
                .ShapeData(_shaper, request.Fields)
                .PaginatedListFromEnumerable(request.PageNumber, request.PageSize)
            );
    }
}

對應(yīng)修改Controller:

TodoItemController.cs

[HttpGet]
public async Task<ApiResponse<PaginatedList<ExpandoObject>>> GetTodoItemsWithCondition([FromQuery] GetTodoItemsWithConditionQuery query)
{
    return ApiResponse<PaginatedList<ExpandoObject>>.Success(await _mediator.Send(query));
}

驗證

啟動Api項目,執(zhí)行查詢TodoItem的請求:

請求

響應(yīng)

我們再把之前講到的過濾和搜索添加到請求里來:

請求

響應(yīng)

總結(jié)

對于數(shù)據(jù)塑形的請求,關(guān)鍵步驟就是使用反射獲取待返回對象的所有配置的可以返回的屬性,再通過前端傳入的屬性名稱進行過濾和值的重組進行返回。實現(xiàn)起來是比較簡單的。但是在實際的使用過程中我不推薦這樣用,除了某些非常適用的特殊場景。個人更偏向于向前端提供明確的接口定義。

到此這篇關(guān)于.NET 6開發(fā)TodoList應(yīng)用之實現(xiàn)數(shù)據(jù)塑形的文章就介紹到這了,更多相關(guān).NET 6數(shù)據(jù)塑形內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • visual studio 2017企業(yè)版本安裝(附序列號)

    visual studio 2017企業(yè)版本安裝(附序列號)

    這篇文章主要介紹了visual studio 2017企業(yè)版本安裝,文末為大家分享了序列號,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-03-03
  • 用.NET Core寫爬蟲爬取電影天堂

    用.NET Core寫爬蟲爬取電影天堂

    本文給大家詳細(xì)介紹了如何使用.NET Core寫爬蟲爬取電影天堂的方法和詳細(xì)步驟,非常的細(xì)致,有需要的小伙伴可以參考下
    2016-12-12
  • 在ashx文件中使用session的解決思路

    在ashx文件中使用session的解決思路

    如果你要保證數(shù)據(jù)的安全性,你可以在ashx中使用session驗證如:你的index.aspx中使用jquery回調(diào)ashx數(shù)據(jù),那么在index.aspx page_load時session[checked]="true",在ashx中驗證session是否存在
    2013-01-01
  • 菜渣開源一個基于?EMIT?的?AOP?庫(.NET?Core)的方法

    菜渣開源一個基于?EMIT?的?AOP?庫(.NET?Core)的方法

    CZGL.AOP?是?基于?EMIT?編寫的?一個簡單輕量的AOP框架,支持非侵入式代理,支持.NET?Core/ASP.NET?Core,以及支持多種依賴注入框架,本文介紹菜渣開源一個基于?EMIT?的?AOP?庫(.NET?Core)的相關(guān)知識,感興趣的朋友一起看看吧
    2024-06-06
  • 解析.Net 4.0 中委托delegate的使用詳解

    解析.Net 4.0 中委托delegate的使用詳解

    本篇文章是對.Net 4.0 中委托delegate的使用進行了詳細(xì)的分析介紹,需要的朋友參考下
    2013-05-05
  • ASP.Net巧用窗體母版頁實例

    ASP.Net巧用窗體母版頁實例

    這篇文章主要介紹了ASP.Net巧用窗體母版頁的方法,以實例形式詳細(xì)分析了母版頁的用途及嵌套用法,具有一定的學(xué)習(xí)借鑒價值,需要的朋友可以參考下
    2014-11-11
  • .net core高吞吐遠(yuǎn)程方法如何調(diào)用組件XRPC詳解

    .net core高吞吐遠(yuǎn)程方法如何調(diào)用組件XRPC詳解

    這篇文章主要給大家介紹了關(guān)于.net core高吞吐遠(yuǎn)程方法如何調(diào)用組件XRPC的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用.net core具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-05-05
  • .NET CORE中比較兩個文件內(nèi)容是否相同的最快方法

    .NET CORE中比較兩個文件內(nèi)容是否相同的最快方法

    這篇文章主要給大家介紹了關(guān)于.NET CORE中比較兩個文件內(nèi)容是否相同的最快方法,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用.NET CORE具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-06-06
  • .NET?Core?使用委托實現(xiàn)動態(tài)流程組裝的思路詳解

    .NET?Core?使用委托實現(xiàn)動態(tài)流程組裝的思路詳解

    模擬管道模型中間件(Middleware)部分,運用委托,進行動態(tài)流程組裝,本次代碼實現(xiàn)就直接我之前寫的動態(tài)代理實現(xiàn)AOP的基礎(chǔ)上改的,就不另起爐灶了,主要思路就是運用委托,具體實現(xiàn)過程跟隨小編一起看看吧
    2022-01-01
  • WPF實現(xiàn)左右移動(晃動)動畫效果

    WPF實現(xiàn)左右移動(晃動)動畫效果

    這篇文章主要為大家詳細(xì)介紹了WPF實現(xiàn)左右移動或晃動動畫效果,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-12-12

最新評論

荥阳市| 南华县| 德江县| 青龙| 姜堰市| 交口县| 永康市| 平陆县| 肥西县| 无棣县| 保靖县| 邻水| 益阳市| 轮台县| 友谊县| 千阳县| 蒙自县| 石屏县| 嘉善县| 施甸县| 安远县| 司法| 宿迁市| 丽水市| 微山县| 镇康县| 宣恩县| 大足县| 壤塘县| 昆山市| 诸城市| 乐平市| 简阳市| 泾阳县| 钟山县| 平原县| 弋阳县| 枣庄市| 蕉岭县| 濮阳县| 萍乡市|