.NET 6开发TodoList应用之实现数据塑形
需求
在查询的场景中,还有一类需求不是很常见,就是在前端请求中指定返回的字段,所以关于搜索的最后一个主题我们就来演示一下关于数据塑形(data shaping)。
目标
实现数据塑形搜索请求。
原理与思路
对于数据塑形来说,我们需要定义一些接口和泛型类实现来完成通用的功能,然后修改对应的查询请求,实现具体的功能。
实现
定义通用接口和泛型类实现
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); }
并实现通用的功能:
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方法调用链能够直接应用,我们在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静态类中添加一个方法:
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接口
我们在实现排序的基础上增加一个字段用于指明数据塑形字段并对应修改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() // 进行数据塑形和分页返回 .shapedata(_shaper, request.fields) .paginatedlistfromenumerable(request.pagenumber, request.pagesize) ); } }
对应修改controller:
todoitemcontroller.cs
[httpget] public async task<apiresponse<paginatedlist<expandoobject>>> gettodoitemswithcondition([fromquery] gettodoitemswithconditionquery query) { return apiresponse<paginatedlist<expandoobject>>.success(await _mediator.send(query)); }
验证
启动api项目,执行查询todoitem的请求:
请求
响应
我们再把之前讲到的过滤和搜索添加到请求里来:
请求
响应
总结
对于数据塑形的请求,关键步骤就是使用反射获取待返回对象的所有配置的可以返回的属性,再通过前端传入的属性名称进行过滤和值的重组进行返回。实现起来是比较简单的。但是在实际的使用过程中我不推荐这样用,除了某些非常适用的特殊场景。个人更偏向于向前端提供明确的接口定义。
到此这篇关于.net 6开发todolist应用之实现数据塑形的文章就介绍到这了,更多相关.net 6数据塑形内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
推荐阅读
-
.NET 6开发TodoList应用之实现DELETE请求与HTTP请求幂等性
-
.NET 6开发TodoList应用实现系列背景
-
.NET 6开发TodoList应用引入数据存储
-
.NET 6开发TodoList应用之使用MediatR实现POST请求
-
.NET 6开发TodoList应用之实现Repository模式
-
.NET 6开发TodoList应用之实现查询分页
-
.NET 6开发TodoList应用之实现ActionFilter
-
.NET 6开发TodoList应用之实现接口请求验证
-
.NET 6开发TodoList应用之实现查询排序
-
.NET 6开发TodoList应用之实现数据塑形