我想使用EF Core执行1次查询,我必须过滤子实体并应用分页。请参阅下面的我(样本)数据模型: 我想检索所有数据(客户,订单订单详情和产品)。我必须在Order.OrderState上应用过滤器,我只想要前10条记录(客户)
这是我试过的LINQ查询:
var customers = await _ctx.Customer
.Include(c => c.Order.Where(o => o.OrderState == 0))
.ThenInclude(o => o.OrderDetail)
.ThenInclude(d => d.Product)
.Skip(0).Take(10)
.ToListAsync();
执行此查询时,我收到以下错误: InvalidOperationException:属性表达式'c => {来自c.Order中的Order o,其中([o] .OrderState == 0)select [o]}'无效。表达式应代表属性访问:'t => t.MyProperty”。有关包含相关数据的更多信息
所以我尝试了另一个问题:
var qry = from c in _ctx.Customer
join o in _ctx.Order on c.Id equals o.CustomerId
join d in _ctx.OrderDetail on o.Id equals d.OrderId
join p in _ctx.Product on d.ProductId equals p.Id
where o.OrderState == 0
select new { Customer = c, Order = o, OrderDetail = d, Product = p };
var customers = await qry.Skip(0).Take(10).ToListAsync();
现在查询不会产生错误,但结果不是我想要的。由于1-n关系,此查询会在结果中多次返回客户,因此我无法获得前10位客户。
有没有人有更好的查询来获得我想要的结果?
答案 0 :(得分:0)
我认为你可以使用" .Distinct()"在构建查询时。希望这能解决问题。
var qry = (from c in _ctx.Customer
join o in _ctx.Order on c.Id equals o.CustomerId
join d in _ctx.OrderDetail on o.Id equals d.OrderId
join p in _ctx.Product on d.ProductId equals p.Id
where o.OrderState == 0
select new { Customer = c, Order = o, OrderDetail = d,
Product = p }).Distinct();
var customers = await qry.Skip(0).Take(10).ToListAsync();