【发布时间】:2021-02-27 19:03:35
【问题描述】:
在 .NET Core 2.2 中,我坚持过滤 IQueryable 构建为:
_context.Ports.Include(p => p.VesselsPorts)
.ThenInclude(p => p.Arrival)
.Include(p => p.VesselsPorts)
.ThenInclude(p => p.Departure)
.OrderBy(p => p.PortLocode);
在多对多关系中。实体模型如:
public class PortModel
{
[Key]
public string PortLocode { get; set; }
public double? MaxKnownLOA { get; set; }
public double? MaxKnownBreadth { get; set; }
public double? MaxKnownDraught { get; set; }
public virtual ICollection<VesselPort> VesselsPorts { get; set; }
}
public class VesselPort
{
public int IMO { get; set; }
public string PortLocode { get; set; }
public DateTime? Departure { get; set; }
public DateTime? Arrival { get; set; }
public VesselModel VesselModel { get; set; }
public PortModel PortModel { get; set; }
}
基于这个this SO answer,我设法创建了这样的LINQ:
_context.Ports.Include(p => p.VesselsPorts).ThenInclude(p => p.Arrival).OrderBy(p => p.PortLocode)
.Select(
p => new PortModel
{
PortLocode = p.PortLocode,
MaxKnownBreadth = p.MaxKnownBreadth,
MaxKnownDraught = p.MaxKnownDraught,
MaxKnownLOA = p.MaxKnownLOA,
VesselsPorts = p.VesselsPorts.Select(vp => vp.Arrival > DateTime.UtcNow.AddDays(-1)) as ICollection<VesselPort>
}).AsQueryable();
但我需要的是找到所有端口记录,其中:
VesselsPorts.Arrival > DateTime.UtcNow.AddDays(-1) 数量大于 int x = 5 值(例如)。而且我不知道该怎么做:/
【问题讨论】:
-
你试过
Where吗? -
是的,您不能在 .NET Core 2.2 中在
Include或IncludeThen上使用Where -
你试过
_context.Ports.Include(p => p.VesselsPorts) .Where(p=>p.VesselsPorts.Count(vp => vp.Arrival > DateTime.UtcNow.AddDays(-1)) > 5) -
您正在投影到
PortModel,因此无论如何都会忽略Includes。而Include与过滤主查询无关。专注于如何过滤端口。我认为类似于_context.Ports.Where(p => p.VesselsPorts.Any(vp => vp.Arrival > DateTime.UtcNow.AddDays(x))。 -
@GertArnold 看起来你可能是对的。现在我只是想知道如何查询所有
ports vaving(vp => vp.Arrival > DateTime.UtcNow.AddDays(-1))至少Count >= 5,例如。
标签: c# linq iqueryable asp.net-core-2.2