3

我们正在使用实体框架来获取一些数据。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();
4

1 回答 1

5

我怀疑主要的性能问题是由于我的主要抱怨。滥用关键字join。

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

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};
于 2013-03-06T08:12:15.770 回答