我希望进行一个EF Core调用,返回一个带有过滤的关联子列表的父对象,并将其投影到dto。我希望通过EF Core Linq查询来实现这一点,我怀疑ProjectTo部分忽略了到那个点的过滤。这可能吗?
- EF Core 5.0
- Automapper 7.0.0
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"
}
]
}
我期望的/想要的
请注意,我只收到了一个子项而不是两个,这是因为其中一个子项的日期在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());
}
Include
。 - Lucian Bargaoanu