C# 提高LINQ查询性能。带有“的查询”;加入;还是小问题?
我得到两个表的ID,并使用它们来验证第三个表中是否有记录 摘要结构表:C# 提高LINQ查询性能。带有“的查询”;加入;还是小问题?,c#,linq,entity-framework-6,C#,Linq,Entity Framework 6,我得到两个表的ID,并使用它们来验证第三个表中是否有记录 摘要结构表: Table 1 (int id1 and string UserName); Table 2 (int id2 and string BranchName); Table 3 (int Id_User and int Id_Branch);//fk table 1 and 2 代码: 此代码结构工作正常,在显示结果之前,我在不同的表中使用了多次(大约5次) 为了能够执行性能测试和比较,您能帮我生成一个统一的查询吗?(可能使
Table 1 (int id1 and string UserName);
Table 2 (int id2 and string BranchName);
Table 3 (int Id_User and int Id_Branch);//fk table 1 and 2
代码:
此代码结构工作正常,在显示结果之前,我在不同的表中使用了多次(大约5次)
为了能够执行性能测试和比较,您能帮我生成一个统一的查询吗?(可能使用连接)这应该将查询合并为一个查询。从您开始使用lambda语法开始,我就使用了lambda语法,不过我认为在这种情况下,流畅的语法可能更容易理解:
var result = (context.Table3.Join(context.Table1, t3 => t3.Id_User, t1 => t1.id1, (t3, t1) => new { t3, t1 })
.Join(context.Table2, t3t1 => t3t1.t3.Id_Branch, t2 => t2.id2, (t3t1, t2) => new { t3t1.t3, t3t1.t1, t2 })
.Where(t3t1t2 => t3t1t2.t1.UserName == user && t3t1t2.t2.BranchName == branch)
)
.Any();
以下是等效的查询语法:
var res2 = (from t3 in context.Table3
join t1 in context.Table1 on t3.Id_User equals t1.id1
join t2 in context.Table2 on t3.Id_Branch equals t2.id2
where t1.UserName == user && t2.BranchName == branch
select t3
)
.Any();
看看如何在1和2上加入表3回答“这会提高性能吗?”问题的唯一方法是尝试并测量影响。我修改了问题。你能帮我在linq中生成统一查询吗?你应该传入useriD和branchid,如果不是你和where的连接,它将位于表上,这些表在你要搜索的列上没有索引,这意味着它将进行完整的表扫描,因此,如果您没有传递这些,您应该使它们成为索引的一部分,以便快速查找!将表3连接到表1和表2(左或内),其中,在名称上,将返回一个,如果名称上有where,那么您将需要在1和2上创建索引,而不是idsI。我同意使用lambda语法会使其更难理解,但它工作得很好,并为其他应用程序提供了一个思路。谢谢。@Sinonim0我添加了一个流畅的版本。我得到了以下错误:查询体必须以select子句或group子句结尾。但是我在最后添加了select t3,它将被修复。@Sinonim0对此很抱歉-我太信任语法检查器了,没有尝试编译代码!您的修复是正确的。请注意:'methodsyntax'和'fluent syntax'(有时还有'lambda syntax')是同义词。后一个例子是“查询语法”或“理解语法”。Fluent syntax是一种使开发人员能够链接方法调用的方法,如
Join().Join().Where().Select()
。EF的fluent mapping API是另一个例子。
var res2 = (from t3 in context.Table3
join t1 in context.Table1 on t3.Id_User equals t1.id1
join t2 in context.Table2 on t3.Id_Branch equals t2.id2
where t1.UserName == user && t2.BranchName == branch
select t3
)
.Any();