提高LINQ查询性能。有“联接”的查询还是较小的查询?

时间:2019-06-25 16:30:55

标签: c# linq entity-framework-6

我获得2个表的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

代码:

...
string user = "NAME1";
string branch = "BRANCH1";

using (A_Entities context= new A_Entities())
{
    //Get user id
    var res1 = context.Table1.SingleOrDefault(x => x.UserName == user);
    int idUser = res1 != null ? res1.id1 : 0;

    //Get branch id
    var res2 = context.Table2.SingleOrDefault(x => x.BranchName == branch);
    int idBranch = res2 != null ? res2.id2 : 0;

    //Validate
    var res3 = context.Table3.SingleOrDefault(x => x.Id_User == idUser && x.Id_Branch == idBranch);
    bool result = res3 != null ? true : false;
}
...

此代码结构正常工作,在显示结果之前,我对不同的表使用了几次(大约5次)。

为了能够进行性能测试和比较,您可以帮助我生成一个统一的查询吗? (也许有联接)

1 个答案:

答案 0 :(得分:0)

这应将查询合并为一个。自从您开始使用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();