gpt4 book ai didi

c# - 使用 Linq Any 查询或表达式构建查询以提高性能

转载 作者:行者123 更新时间:2023-11-29 15:37:18 24 4
gpt4 key购买 nike

我们的项目中是 Entity Framework 。需要了解 .ANY() 与形成Where子句的表达式之间的性能影响。

在下面的函数中,我使用了两种方法来获取结果:

方法 1 - 使用 ANY() 形成 Lambda 表达式查询根据我的观察,使用 .Any() 不会在执行查询时添加 where 子句(在 sql profiler 中检查),EF 所做的是获取所有匹配的内部连接记录存储在内存中,然后应用 .ANY() 中指定的条件

方法 2 - 表单表达式查询启动使用表达式,我显式地形成 where 子句并执行。在 SQL 查询探查器中检查相同的情况,我可以看到 where 子句。注意:为了形成表达式 where 子句,我正在执行额外的循环和“CombinePredicates”。

现在,我的疑问是:

  1. 哪种方法可以提高性能。我需要和 Lambda 一起去吗与 .ANY() 或表达式?

  2. 使用 from where 子句提高性能的正确方法是什么?

如果不是,这两种方法建议我正确的方法

private bool GetClientNotifications(int clientId, IList<ClientNotification> clientNotifications)
{
IList<string> clientNotificationList = null;
var clientNotificationsExists = clientNotifications?.Select(x => new { x.Name, x.notificationId
}).ToList();
if (clientNotificationsExists?.Count > 0)
{

//**Approach 1 => Form Lamada Query starts**
notificationList = this._clientNotificationRepository?.FindBy(x => clientNotificationsExists.Any(x1 => x.notificationId == x1.notificationId && x.clientId ==
clientId)).Select(x => x.Name).ToList();
**//Form Lamada Query Ends**

//**Approach 2 =>Form Expression Query Starts**
var filterExpressions = new List<Expression<Func<DbModel.ClientNotification, bool>>>();
Expression<Func<DbModel.ClientNotification, bool>> predicate = null;
foreach (var clientNotification in clientNotificationsExists)
{
predicate = a => a.clientId == clientId && a.notificationId == clientNotification .notificationId;
filterExpressions.Add(predicate);
}
predicate = filterExpressions.CombinePredicates<DbModel.ClientNotification>(Expression.OrElse);
clientNotificationList = this._clientNotificationRepository?.FindBy(predicate).Select(x => x.Name).ToList();
//**Form Expression Query Ends**
}
return clientNotificationList;
}

如果没有一种方法是好的,请建议我正确的方法。

最佳答案

我注意到两种方法中使用的 clientId 都用于链接到 clientNotificationsExists 的条件,但与其对象没有实际关系,因此该条件可以上移一级。这可能会带来微小的好处,因为如果没有重复的子句,整个 SQL 将会更小。

从所描述的行为来看,第一个方法过滤器没有被转换为 sql,因此它正在客户端解析,但是,如果可以转换,性能将相似或相同。

如果要生成 IN sql 子句,您可以使用数组并在过滤表达式中使用 Contains 方法。这也许会有所改善,但不要抱太大希望。

尝试以下操作:

private bool GetClientNotifications(int clientId, IList<ClientNotification> clientNotifications)
{
IList<string> clientNotificationList = null;
var clientNotificationsExists = clientNotifications?
.Select(x => new { x.Name, x.notificationId }).ToList();
if (clientNotificationsExists?.Count > 0)
{
var notificationIds = clientNotificationsExists.Select(x => x.notificationId).ToArray();
clientNotificationList = this._clientNotificationRepository?
.FindBy(x => x.clientId == clientId && notificationIds.Contains(x.notificationId));
}
return clientNotificationList;
}

关于c# - 使用 Linq Any 查询或表达式构建查询以提高性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58111627/

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