0

有一个我现在要预编译的 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 {} 语法有关。在我编写的其他预编译查询中,我不得不自己使用选择投影。在这种情况下,我需要执行 grp.count() 和立即 if 逻辑。

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

4

1 回答 1

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; }
}
于 2010-04-26T23:40:16.060 回答