gpt4 book ai didi

c# - Entity Framework 中的 Linq 查询优化

转载 作者:搜寻专家 更新时间:2023-10-30 22:23:45 25 4
gpt4 key购买 nike

我有以下查询,我正在寻找的是优化 where 子句。我不喜欢多次使用 FirstOrDefault。有没有一种方法可以通过 Join 或其他方式来实现它,这样我就可以只访问一次 FirstOrDefault

var promos = await this._context
.SinglePromotions
.Include(p => p.Rewards)
.Include(p => p.InAppProduct)
.Include(p => p.PlayerSinglePromotions)
.ThenInclude(sp => sp.Player)
.ThenInclude(pl => pl.Purchases)
.Where(p => p.MinimumPlayerLevel <= Player.Level &&
p.Placement == placement &&
p.IsActive &&
(p.PlayerSinglePromotions.All(sp => sp.PlayerID != Player.ID) ||
(p.PlayerSinglePromotions.FirstOrDefault(sp => sp.PlayerID == Player.ID).PurchaseAmount < p.PurchaseLimit)) &&
(p.PlayerSinglePromotions.All(sp => sp.PlayerID != Player.ID) || (p.PlayerSinglePromotions.FirstOrDefault(sp => sp.PlayerID == Player.ID).Player.Purchases.Count <= p.MaxInAppPurchasesByPlayer))
)
.ToListAsync();

最佳答案

嗯,可能有更好的解决方案,但您可以使用 Any 扩展方法替换使用 FirstOrDefault 的条件:

var promos = await this._context.SinglePromotions
.Include(p => p.Rewards)
.Include(p => p.InAppProduct)
.Include(p => p.PlayerSinglePromotions)
.ThenInclude(sp => sp.Player)
.ThenInclude(pl => pl.Purchases)
.Where(
p => p.MinimumPlayerLevel <= Player.Level &&
p.Placement == placement &&
p.IsActive &&
(p.PlayerSinglePromotions.All(sp => sp.PlayerID != Player.ID) ||
p.PlayerSinglePromotions.Any(sp => sp.PlayerID == Player.ID
&& (sp.Player.Purchases.Count <= p.MaxInAppPurchasesByPlayer || sp.PurchaseAmount < p.PurchaseLimit))))
.ToListAsync();

关于c# - Entity Framework 中的 Linq 查询优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56479522/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com