【发布时间】:2016-06-23 16:22:57
【问题描述】:
我的 ASP.Net 应用程序具有以下 Linq to SQL 函数,用于从产品表中获取不同的高度值列表。
public static List<string> getHeightList(string catID)
{
using (CategoriesClassesDataContext db = new CategoriesClassesDataContext())
{
var heightTable = (from p in db.Products
join cp in db.CatProducts on p.ProductID equals cp.ProductID
where p.Enabled == true && (p.CaseOnly == null || p.CaseOnly == false) && cp.CatID == catID
select new { Height = p.Height, sort = Convert.ToDecimal(p.Height.Replace("\"", "")) }).Distinct().OrderBy(s => s.sort);
List<string> heightList = new List<string>();
foreach (var s in heightTable)
{
heightList.Add(s.Height.ToString());
}
return heightList;
}
}
我运行了 Redgate SQL Monitor,它显示此查询正在使用大量资源。
Redgate 还显示我正在运行以下查询:
select count(distinct [height]) from product p
join catproduct cp on p.productid = cp.productid
join cat c on cp.catid = c.catid
where p.enabled=1 and p.displayfilter = 1 and c.catid = 'C2-14'
我的问题是:
- 建议更改函数以减少资源占用?
- 另外,linq to sql 如何从我的函数生成上述查询? (我没有在代码的任何地方写 select count(distinct [height]) from product)
产品中有 90,000 条记录。我试图获得不同高度列表的这个类别有 50,000 条产品记录
提前谢谢你,
尼克
【问题讨论】:
-
将该 SQL 复制到 SQL Server Management Studio 并获取执行计划。将执行计划与您的问题一起发布。 cat.catid 是索引还是键?
-
您发布的 sql 查询和 linq 查询根本不匹配
-
您是否在 Management Studio 中尝试过该查询?使用预期执行计划函数对其进行调查。如果您缺少表上的索引,这可能会给您一个提示
-
如果你不知道如何使用执行计划,你可以看看这里:mssqltips.com/sqlservertutorial/285/query-execution-plans
-
如果你使用
heightTable.ToString(),你应该会得到它将产生的查询。
标签: c# sql-server linq