我有这个 linq 查询,它查询一个表,该表保留对任何表所做的任何更改历史记录,其构造如下:
History (Primary Key) | Table_Name | Primary_Key | Field_Name | Old_Value | New_Value | Action_Type | Action_Date | Action_User
我查询此表的 linq 查询是这样的:
var complaintHistory = from histories in DbContext.Histories
where ((from c in taskIds
select "<Task_ID=" + c + ">").Contains(histories.Primary_Key) ||
(from c in notificationListIds
select "<Notification_List_ID=" + c + ">").Contains(histories.Primary_Key) ||
(from c in emailSentIds
select "<Email_Sent_ID=" + c + ">").Contains(histories.Primary_Key) ||
histories.Primary_Key == "<Complaint_ID=" + Complaint.Complaint_ID + ">") &&
histories.Field_Name != "rowversion"
select histories;
每当调用此查询时,我都会遇到严重的延迟。是否可以重写此 linq 查询以显着提高性能,或者我是不是想在没有桨的情况下上河?
请您参考如下方法:
总是在性能不好时首先查看生成的 SQL。你会发现这很可怕。它包含许多UNION s 个单行表,其中字符串 from c in taskIds select "<Task_ID=" + c + ">"等等。
请记住,整个查询都被翻译成 SQL。如果你只有...
where taskIds.Contains(histories.Primary_Key)
...等等,那么这些谓词可以被翻译成IN声明。在您的查询中,组合字符串 "<Task_ID=" + c + ">"必须用笨拙的 SQL 构建。这足以拉低查询优化器。此外,taskIds 中的元素数量极大地影响性能并且不需要很多元素(~50)就可以达到最大嵌套级别。
首先要尝试的是减轻数据库引擎构建这些组合字符串的负担,方法是先自己做:
var task_Ids = (from c in taskIds
select "<Task_ID=" + c + ">").ToArray();
和
where task_Ids.Contains(histories.Primary_Key)
其他两个 ID 列表相同。
如果taskIds不包含太多元素(不是数千)您还可以构建一个包含三个字符串组合的列表:
var ids = (from c in taskIds select "<Task_ID=" + c + ">")
.Union(
(from c in taskIds select "<Notification_List_ID="" + c + ">"))
.Union(
(from c in taskIds select "<Email_Sent_ID=" + c + ">"))
.ToArray();
并且只使用一个Contains声明。
更根本的是,我认为您不应该以这种形式存储主键。它混合了数据和特定的表示实现(这本身就够邪恶了)并且不必要地使查询复杂化。如果 Primary_Key 会容易得多本来是一个简单的值,等于原始记录,可能在一个复合键中,其类型字段确定 Task , Notification等
