我们正在使用 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/