C# 如何改进Linq到Sql代码

C# 如何改进Linq到Sql代码,c#,sql,linq-to-sql,profiling,mvc-mini-profiler,C#,Sql,Linq To Sql,Profiling,Mvc Mini Profiler,使用StackExchange.Profiling.MiniProfiler类分析一个ASP.NET MVC应用程序,将Linq to Sql作为ORM 我试图将一个操作简化为一个SQL,这样我就不会再有任何重复的操作了。 因此,我相应地将linq代码更改为sql代码,但这对速度没有任何积极影响 然后我检查了SQL所需的时间 这将显示MiniProfiler: 在Management Studio中启动完全相同的SQL时,速度非常快: 代码如下: from t in type let tDo

使用
StackExchange.Profiling.MiniProfiler
类分析一个ASP.NET MVC应用程序,将Linq to Sql作为ORM

我试图将一个操作简化为一个SQL,这样我就不会再有任何重复的操作了。 因此,我相应地将linq代码更改为sql代码,但这对速度没有任何积极影响

然后我检查了SQL所需的时间

这将显示MiniProfiler:

在Management Studio中启动完全相同的SQL时,速度非常快:

代码如下:

from t in type
let tDoc = (from d in context.documents
            where d.Key == t.No
            && d.RType == (int)RType.Art
            && d.AType == (int)AType.Doc
            select d).FirstOrDefault(d => d.UseForThumb)
select new Time
{
    Id = t.Id,
    //... more simple mappings here
    // then a complex one:
    DocsCount = context.documents.Count(d =>
        (d.Key == t.Id.ToString()
        && d.RType == (int)RType.Type
        && d.AType == (int)AType.Doc)
        ||
        (d.Key == t.No
        && d.RType == (int)RType.Art
        && d.AType == (int)AType.Doc)),

    // and another one
    ThumbId = (tDoc != null && tDoc.FRKey.HasValue) ? tDoc.FRKey.Value : 0
};
造成如此巨大差异的原因是什么编辑:没有区别,我只是错误地解释了SSM:(

不管怎样,我的问题仍然存在。我可以做些什么来加快它


我有时读到从Linq到Sql的映射存在性能问题。有没有办法解决这个问题?

我做了一些尝试,并将Linq到Sql的代码更改为:

from t in types
let docs = context.documents.Where(d => (d.RKey == t.Id.ToString()
                                     && d.RType == (int)RType.Type
                                     && d.AType == (int)AType.Doc)
                                   ||
                                        (d.RKey == t.No 
                                     && d.RType == (int)RType.Art 
                                     && d.AType == (int)AType.Doc))
let tDoc = docs.FirstOrDefault(d => d.RType == (int)RType.Art && d.UseForThumb)
let docsCount = docs.Count()
select new Time
{                                               
  Id = t.Id,
  //... more simple mappings here
  DocsCount = docsCount,
  ThumbId = (tDoc != null && tDoc.FRKey.HasValue) ? tDoc.FRKey.Value : 0,
}

这使得查询速度大大加快。

您的代码和SSMS的性能都是一样的:1秒,不是吗?哦,是这样吗?我想在SSMS中是1ms!令人尴尬!获取这12行仍然很慢…使用fdottrace来找出发生了什么,别再猜测了!我用Sql Server Profiler在Sql Server上启动了跟踪,并得到了有很多信息,但我还不知道如何处理它…所以我现在正在边做边学。我也会尝试fdottrace。您的问题不在于sql server,请使用dottrace找出代码的哪一部分比较慢:模板、sql、计算。。。