c# - Linq on Entity Framework 与 SQL 存储过程的性能对比

标签 c# performance linq entity-framework

我们正在使用 Entity Framework 来获取一些数据。 LINQ 查询使用多个连接,如下面的代码所示。我被要求将其更改为 SQL 存储过程,因为它更快。我如何优化这个 LINQ 代码,为什么它很慢?

var brands = (from b in entity.tblBrands
                          join m in entity.tblMaterials on b.BrandID equals m.BrandID
                          join bm in entity.tblBranchMaterials on m.MaterialID equals bm.MaterialID
                          join br in entity.tblBranches on bm.BranchID equals br.BranchID
                          where br.BranchID == branch.branchId
                          select new Brand { brandId=b.BrandID, brandName=b.BrandName, SAPBrandId=b.SAPBrandID}).Distinct();
            return brands.ToList();

最佳答案

我怀疑主要的性能问题是由于我的一个主要提示。滥用关键字 join。

由于使用了 JOIN,您得到的结果太多。因此,您随后使用了 DISTINCT。更糟糕的是,您对外部结果集执行了此操作,而 SQL Server 在该结果集上没有索引。

var brands = from b in context.Brands
where 
    (from m in context.Materials 
        where b.BrandID == m.BrandID 
        where (from bm in context.BranchMaterials 
                where (from br in context.Branches
                        where bm.BranchID == br.BranchID
                        where br.BranchID == branch.branchId
                        select br).Any()
                where m.MaterialID == bm.MaterialID select bm).Any()
        select m).Any()
    ).Any()
select b;

应该更高效。然而,这仍然是错误的。因为在使用 ORM 时,我们应该考虑 ASSOCIATIONS 而不是 JOIN。假设您的模型有意义,我会执行以下操作。

var brands = from b in context.Brands
             where (from m in b.Materials
                    //Assuming that BranchMaterials is just a Many-Many mapping table
                    from br in m.Branches
                    where br.BranchID == branch.branchId).Any()     
                select new Brand { brandId=b.BrandID, brandName=b.BrandName, SAPBrandId=b.SAPBrandID};

关于c# - Linq on Entity Framework 与 SQL 存储过程的性能对比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15240711/

相关文章:

c# - Regex.Replace 中的 MatchEvaluator 如何工作?

c# - 有没有办法直接从 C# 中的 Amazon S3 制表符分隔文件批量插入 Amazon Aurora RDS?

c# - 不移动光标修改文本框

c# - 使用 XDocument 删除空元素

自定义语言的 C# 所见即所得编辑器

c++ - 操作不同类型变量的速度有什么区别吗?

java - 如何在EditText中进行正常的行编号?

mysql - 将数据存储在一张大表中或每月创建新表

c# - 访问对象属性而不转换为类型

c# - 使用最小起订量模拟 Linq `Any` 谓词