实体框架上Linq与SQL存储过程的性能比较
本文关键字:性能 性能比 比较 存储过程 SQL 框架 Linq 实体 | 更新日期: 2023-09-27 18:02:23
我们正在使用实体框架来获取一些数据。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时,我们应该考虑关联而不是连接。假设您的模型是有意义的,我将执行以下操作。
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};