LinqtoSql在Group by上使用Count()预编译查询问题

时间:2010-04-26 23:25:09

标签: c# linq-to-sql precompiled

有一个我现在想要预编译的LinqtoSql查询。

var unorderedc =
            from insp in sq.Inspections
            where insp.TestTimeStamp > dStartTime && insp.TestTimeStamp < dEndTime
                && insp.Model == "EP" && insp.TestResults != "P"
            group insp by new { insp.TestResults, insp.FailStep } into grp

            select new
            {

                FailedCount = (grp.Key.TestResults == "F" ? grp.Count() : 0),
                CancelCount = (grp.Key.TestResults == "C" ? grp.Count() : 0),
                grp.Key.TestResults,
                grp.Key.FailStep,
                PercentFailed = Convert.ToDecimal(1.0 * grp.Count() / tcount * 100)

            };

我创建了这个委托:

public static readonly Funct<SQLDataDataContext, int, string, string, DateTime, DateTime, IQueryable<CalcFailedTestResult>>
    GetInspData = CompiledQuery.Compile((SQLDataDataContext sq, int tcount, string strModel, string strTest, DateTime dStartTime,
    DateTime dEndTime, IQueryable<CalcFailedTestResult> CalcFailed) =>
    from insp in sq.Inspections
            where insp.TestTimeStamp > dStartTime && insp.TestTimeStamp < dEndTime
                && insp.Model == strModel && insp.TestResults != strTest
            group insp by new { insp.TestResults, insp.FailStep } into grp
            select new 
            {
                FailedCount = (grp.Key.TestResults == "F" ? grp.Count() : 0),
                CancelCount = (grp.Key.TestResults == "C" ? grp.Count() : 0),
                grp.Key.TestResults,
                grp.Key.FailStep,
                PercentFailed = Convert.ToDecimal(1.0 * grp.Count() / tcount * 100)
            });

语法错误在CompileQuery.Compile()语句

它似乎与select new {}语法的使用有关。 在我编写的其他预编译查询中,我不得不自己使用select投影。在这种情况下,我需要执行grp.count()和立即if逻辑。

我搜索了SO和其他参考资料但找不到答案。

1 个答案:

答案 0 :(得分:0)

简而言之,你不能拥有一个匿名类型的CompliedQuery,你需要让查询返回一个命名类型,所以你的

select new 
        {
            FailedCount = (grp.Key.TestResults == "F" ? grp.Count() : 0),
            CancelCount = (grp.Key.TestResults == "C" ? grp.Count() : 0),
            grp.Key.TestResults,
            grp.Key.FailStep,
            PercentFailed = Convert.ToDecimal(1.0 * grp.Count() / tcount * 100)
        }

现在是:

select new MyType
        {
            FailedCount = (grp.Key.TestResults == "F" ? grp.Count() : 0),
            CancelCount = (grp.Key.TestResults == "C" ? grp.Count() : 0),
            TestResults = grp.Key.TestResults,
            FailStep = grp.Key.FailStep,
            PercentFailed = Convert.ToDecimal(1.0 * grp.Count() / tcount * 100)
        }

Func<>的最后一个通用参数也是IQueryable<MyType>,因为这就是您的查询现在返回的内容。

在这种情况下,MyType看起来像:

public class MyType {
  public int FailedCount { get; set; }
  public int CancelCount { get; set; }
  public string TestResults { get; set; }
  public string FailStep { get; set; } //Unsure of type here
  public decimal PercentFailed { get; set; }
}