c# - EF Core 和 Automapper - 过滤子记录
问题描述
我想进行一个 EF Core 调用,该调用返回一个父对象,该对象具有过滤后的关联子项列表,并将其投影到 dto。我想通过 EF Core Linq 查询来做到这一点,我怀疑 ProjectTo 部分忽略了到目前为止的过滤。是否可以?
- EF 核心 5.0
- 自动映射器 7.0.0
我有另一个查询,它获取父项并包含所有没有过滤器的子记录,所以如果可能的话,我想在 Dto 映射配置之外实现一些东西。
域对象
public class ParentThing
{
public Guid Id { get; set; }
public string Name { get; set; }
public List<ChildThing> ChildThings { get; set; }
}
public class ChildThing
{
public Guid Id { get; set; }
public Guid ParentThingId { get; set; }
public DateTime Date { get; set; }
public ParentThing ParentThing { get; set; }
}
Dtos
public class ParentThingDto : IMapFrom<ParentThing>
{
public Guid Id { get; set; }
public string Name { get; set; }
public List<ChildThingDto> ChildThings { get; set; }
}
public class ChildThingDto : IMapFrom<ChildThing>
{
public Guid Id { get; set; }
public DateTime Date { get; set; }
}
询问
var upUntilDate = new DateTime(2013,1,1);
return await _context.ParentThings
.Where(x => x.Id == request.ParentThingId)
.Include(x => x.ChildThings.Where(y => y.Date <= upUntilDate))
.ProjectTo<ParentThingDto>(_mapper.ConfigurationProvider)
.FirstOrDefaultAsync();
我得到了什么
{
"id": "a5c8f72a-4682-4f62-b231-4c77c0615b84",
"name": "Parent thing 9",
"childThings": [
{
"id": "ff5fda07-1c15-411c-b72e-e126b91513b3",
"date": "2014-06-26T22:41:20.7141034"
},
{
"id": "4dded8a3-2231-442e-b40a-1e114da2665a",
"date": "2012-04-02T06:51:31.963399"
}
]
}
我期望/想要的
请注意,我只得到一个孩子的东西而不是 2,这是因为一个孩子有一个日期,之后2013-01-01
是我想要的过滤点。
{
"id": "a5c8f72a-4682-4f62-b231-4c77c0615b84",
"name": "Parent thing 9",
"childThings": [
{
"id": "4dded8a3-2231-442e-b40a-1e114da2665a",
"date": "2012-04-02T06:51:31.963399"
}
]
}
只是一个说明IMapFrom<T>
只做以下
public interface IMapFrom<T>
{
void Mapping(Profile profile) => profile.CreateMap(typeof(T), GetType());
}
解决方案
当您通过手动或使用 AutoMapper投影到自定义 dto 投影时, AFAIKInclude
不起作用。Select
相反,使用自定义配置文件
public class CustomProfile : Profile
{
public CustomProfile()
{
DateTime? upUntilDate = null;
CreateMap<ParentThing, ParentThingDto>()
.ForMember(m => m.ChildThings, opt =>
opt.MapFrom(m => m.ChildThings.Where(y =>
upUntilDate.HasValue ? y.Date <= upUntilDate : true))
);
}
}
然后当您投影时,您将upUntilDate
参数添加到ProjectTo
var upUntilDate = new DateTime(2013,1,1);
return await _context.ParentThings
.Where(x => x.Id == request.ParentThingId)
.ProjectTo<ParentThingDto>(_mapper.ConfigurationProvider, new { upUntilDate })
.FirstOrDefaultAsync();
如果您不想过滤子项,只需将 upUntilDate 设置为 null(或不添加参数)。
推荐阅读
- typescript - TypeORM:如何在由一对多支持的实体上拥有字符串数组属性?
- bash - 为什么循环只运行 1 次而不是到达文件末尾?
- javascript - 将新源设置为 Audio Element 后如何中止下载 .mp3 文件?
- python - 如何引发坐标超出栅格边界(rasterio.sample)的错误?
- load-balancing - 如何实现具有持久连接的有状态应用程序的负载平衡 - Envoy 和 Rsocket
- c - 从文件中填充 C 中的嵌套结构的正确方法
- node.js - 将localstorage中的数据同步到mongodb
- c - 为什么随机测试用例会出现“运行时错误:分段错误”?
- delphi - 我可以在不使用位图的情况下更改肤色吗?
- node.js - Cloud Run Build 期间未定义环境变量