12

考虑下面的代码:

StockcheckJobs = 
     (from job in (from stockcheckItem in MDC.StockcheckItems
                   where distinctJobs.Contains(stockcheckItem.JobId)
                   group stockcheckItem by new { stockcheckItem.JobId, stockcheckItem.JobData.EngineerId } into jobs
                   select jobs).ToList()
      let date = MJM.GetOrCreateJobData(job.Key.JobId).CompletedJob.Value
      orderby date descending 
      select new StockcheckJobsModel.StockcheckJob()
      {
          JobId = job.Key.JobId,
          Date = date,
          Engineer = (EngineerModel)job.Key.EngineerId,
          MatchingLines = job.Count(sti => sti.Quantity == sti.ExpectedQuantity),
          DifferingLines = job.Count(sti => sti.Quantity != sti.ExpectedQuantity)
      }).ToList()

ToList()中间有个a ,因为GetOrCreateJobData方法不能翻译成sql。

结果,我不得不将查询的第一部分括在括号中才能做到这一点,然后我使用了外部查询来完成。

我知道我可以将其拆分为两个变量,但我不想这样做(这也在对象初始化程序中)。

ToList当我必须在 linq 查询中间执行(或以其他方式访问 linq-to-objects)时,是否可以使用其他语法来提高可读性,最好消除对外部和内部查询的需要?


在一个理想的世界中,我想要这样的东西(尽可能接近):

StockcheckJobs =
     from stockcheckItem in MDC.StockcheckItems
     where distinctJobs.Contains(stockcheckItem.JobId)
     group stockcheckItem by new { stockcheckItem.JobId, stockcheckItem.JobData.EngineerId } into jobs
     MAGIC_DO_BELOW_AS_LINQ-TO-OBJECTS_KEYWORD_OR_SYNTAX
     let date = MJM.GetOrCreateJobData(jobs.Key.JobId).CompletedJob.Value
     orderby date descending 
     select new StockcheckJobsModel.StockcheckJob()
     {
         JobId = jobs.Key.JobId,
         Date = date,
         Engineer = new ThreeSixtyScheduling.Models.EngineerModel() { Number = jobs.Key.EngineerId },
         MatchingLines = jobs.Count(sti => sti.Quantity == sti.ExpectedQuantity),
         DifferingLines = jobs.Count(sti => sti.Quantity != sti.ExpectedQuantity)
     };
4

4 回答 4

5

您可以解决GetOrCreateJobData无法转换为 SQL 的问题。

通过为指定的方法调用表达式实现自定义查询转换器,您可以控制 LINQ-to-SQL 如何解释该方法。有一篇很好的文章解释了这个过程并链接到相关资源:http: //www.codeproject.com/Articles/32968/QueryMap-Custom-translation-of-LINQ-expressions

或者,您可以将该方法重构为GetOrCreateJobData使用表达式构建相同逻辑的扩展方法,以便 LINQ-to-SQL 可以自然地解释它。根据方法的复杂性,这可能比我的第一个建议或多或少可行。

于 2012-09-20T15:21:45.317 回答
3

我发现使用方法语法会使事情更清楚,但这只是个人喜好。它确实使查询的上半部分更好,但使用 a let,虽然在方法语法中是可能的,但工作量更大。

var result = stockcheckItem in MDC.StockcheckItems
    .Where(item => distinctJobs.Contains(item.JobId))
    .GroupBy(item => new { item.JobId, item.JobData.EngineerId })
    .AsEnumerable() //switch from Linq-to-sql to Linq-to-objects
    .Select(job => new StockcheckJobsModel.StockcheckJob()
    {
        JobId = job.Key.JobId,
        Date = MJM.GetOrCreateJobData(job.Key.JobId).CompletedJob.Value,
        Engineer = (EngineerModel)job.Key.EngineerId,
        MatchingLines = job.Count(sti => sti.Quantity == sti.ExpectedQuantity),
        DifferingLines = job.Count(sti => sti.Quantity != sti.ExpectedQuantity)
    })
    .Orderby(item => item.Date)
    .ToList()
于 2012-09-20T15:33:39.733 回答
3

对于这个问题,我要提出两点:

  1. 我真的不认为在这里引入一个额外的变量有任何可读性问题。事实上,我认为它使它更具可读性,因为它将“本地执行”代码与在数据库上执行的代码分开。
  2. 要简单地切换到 LINQ-To-Objects,AsEnumerable最好使用ToList.

也就是说,这就是您如何在整个查询表达式上没有中间 AsEnumerable() / ToList() 的情况下一直停留在查询区域:通过欺骗 C# 编译器使用您的自定义扩展方法而不是 BCL。这是可能的,因为 C# 使用“基于模式”的方法(而不是与 BCL 耦合)将查询表达式转换为方法调用和 lambda。

像这样声明邪恶的类:

public static class To
{
    public sealed class ToList { }

    public static readonly ToList List;

    // C# should target this method when you use "select To.List"
    // inside a query expression.
    public static List<T> Select<T>
        (this IEnumerable<T> source, Func<T, ToList> projector)
    {
        return source.ToList();
    }
}

public static class As
{
    public sealed class AsEnumerable { }

    public static readonly AsEnumerable Enumerable;

    // C# should target this method when you use "select As.Enumerable"
    // inside a query expression.
    public static IEnumerable<T> Select<T>
        (this IEnumerable<T> source, Func<T, AsEnumerable> projector)
    {
        return source;
    }
}

然后您可以编写如下查询:

List<int> list = from num in new[] { 41 }.AsQueryable()
                 select num + 1 into result
                 select To.List;

IEnumerable<int> seq = from num in new[] { 41 }.AsQueryable()
                       select num + 1 into result
                       select As.Enumerable into seqItem
                       select seqItem + 1; // Subsequent processing

在您的情况下,您的查询将变为:

StockcheckJobs =
     from stockcheckItem in MDC.StockcheckItems
     where distinctJobs.Contains(stockcheckItem.JobId)
     group stockcheckItem by new { stockcheckItem.JobId, stockcheckItem.JobData.EngineerId } into jobs
     select As.Enumerable into localJobs // MAGIC!
     let date = MJM.GetOrCreateJobData(localJobs.Key.JobId).CompletedJob.Value
     orderby date descending 
     select new StockcheckJobsModel.StockcheckJob()
     {
         JobId = localJobs.Key.JobId,
         Date = date,
         Engineer = new ThreeSixtyScheduling.Models.EngineerModel() { Number = localJobs.Key.EngineerId },
         MatchingLines = localJobs.Count(sti => sti.Quantity == sti.ExpectedQuantity),
         DifferingLines = localJobs.Count(sti => sti.Quantity != sti.ExpectedQuantity)
     };

不过,我真的不认为这是一种改进。相反,这是对语言功能的严重滥用。

于 2012-09-20T15:46:06.120 回答
0

一种选择是将所有与 SQL 兼容的工作预先转换为匿名类型,

var jobs = 
     (from job in (from stockcheckItem in MDC.StockcheckItems
        where distinctJobs.Contains(stockcheckItem.JobId)
        group stockcheckItem by new 
             { stockcheckItem.JobId, stockcheckItem.JobData.EngineerId } 
         into jobs
        select new 
             {
                JobId = job.Key.JobId,
                Engineer = (EngineerModel)job.Key.EngineerId,
                MatchingLines = 
                    job.Count(sti => sti.Quantity == sti.ExpectedQuantity),
                DifferingLines = 
                    job.Count(sti => sti.Quantity != sti.ExpectedQuantity)
             }
      ).AsEnumerable()

StockcheckJobs = jobs.Select(j => new StockcheckJobsModel.StockcheckJob
    {
         JobId = j.JobId,
         Date = MJM.GetOrCreateJobData(j.JobId).CompletedJob.Value,
         Engineer = j.EngineerId,
         MatchingLines = j.MatchingLines,
         DifferingLines = j.DifferingLines
    }).OrderBy(j => j.Date).ToList();

显然没有经过测试,但你明白了。

于 2012-09-20T15:26:01.317 回答