使用LINQ插入/选择-绕过查询中的实体构造

本文关键字:查询 实体 插入 LINQ 选择 使用 | 更新日期: 2024-09-23 21:08:16

我已经阅读了关于错误"不允许在查询中显式构造实体类型"的几个问题,以及解决它的各种方法。

  • 实体类型的显式构造'###';不允许在查询中
  • 不允许在查询中显式构造实体类型[MyClass]
  • 实体类型的显式构造'';不允许在查询中

我在代码中使用DBML自动生成的LINQ到SQL类,因此能够适当地选择和插入数据将是一件很棒的事情。以下是另一篇文章中提出的一种方法;在下面的示例中,e_activeSession是DataContext:中表的自动生成表示

var statistics =
    from record in startTimes
    group record by record.startTime into g
    select new e_activeSession
            {
                workerId = wcopy,
                startTime = g.Key.GetValueOrDefault(),
                totalTasks = g.Count(),
                totalTime = g.Max(o => o.record.timeInSession).GetValueOrDefault(),
                minDwell = g.Min(o => o.record.dwellTime).GetValueOrDefault(),
                maxDwell = g.Max(o => o.record.dwellTime).GetValueOrDefault(),
                avgDwell = g.Average(o => o.record.dwellTime).GetValueOrDefault(),
                stdevDwell = g.Select(o => Convert.ToDouble(o.record.dwellTime)).StdDev(),
                total80 = g.Sum(o => Convert.ToInt16(o.record.correct80) + Convert.ToInt16(o.record.wrong80)),
                correct80 = g.Sum(o => Convert.ToInt16(o.record.correct80)),
                percent80 = Convert.ToDouble(g.Sum(o => Convert.ToInt16(o.record.correct80))) /
                            g.Sum(o => Convert.ToInt16(o.record.correct80) + Convert.ToInt16(o.record.wrong80))
            };

上面抛出了错误,所以我尝试了以下操作:

var groups =
    from record in startTimes
    group record by record.startTime
    into g
    select g;
var statistics = groups.ToList().Select(
    g => new e_activeSession
             {
                 workerId = wcopy,
                 startTime = g.Key.GetValueOrDefault(),
                 totalTasks = g.Count(),
                 totalTime = g.Max(o => o.record.timeInSession).GetValueOrDefault(),
                 minDwell = g.Min(o => o.record.dwellTime).GetValueOrDefault(),
                 maxDwell = g.Max(o => o.record.dwellTime).GetValueOrDefault(),
                 avgDwell = g.Average(o => o.record.dwellTime).GetValueOrDefault(),
                 stdevDwell = g.Select(o => Convert.ToDouble(o.record.dwellTime)).StdDev(),
                 total80 = g.Sum(o => Convert.ToInt16(o.record.correct80) + Convert.ToInt16(o.record.wrong80)),
                 correct80 = g.Sum(o => Convert.ToInt16(o.record.correct80)),
                 percent80 = Convert.ToDouble(g.Sum(o => Convert.ToInt16(o.record.correct80))) /
                             g.Sum(o => Convert.ToInt16(o.record.correct80) + Convert.ToInt16(o.record.wrong80))
             });

然而,ToList的效率似乎非常低,只会让我的代码在那里停留很长一段时间。有更好的方法吗?

使用LINQ插入/选择-绕过查询中的实体构造

AsEnumerable()将与ToList()做相同的事情,将处理带入对象的linq中,但不会浪费时间和内存先存储所有对象。相反,当您遍历它时,它会一次创建一个对象。

通常,您应该使用AsEnumerable()将操作从另一个源移动到内存中,而不是ToList(),除非您真的想要一个列表(例如,如果您将多次访问相同的数据,则该列表充当缓存)。

到目前为止,我们有:

var statistics = (
  from record in startTimes
  group record by record.startTime
  into g
  select g;
  ).AsEnumerable().Select(
    g => new e_activeSession
    {
      workerId = wcopy,
      startTime = g.Key.GetValueOrDefault(),
      totalTasks = g.Count(),
      totalTime = g.Max(o => o.record.timeInSession).GetValueOrDefault(),
      /* ... */
     });

但还有一个更大的问题。你也要小心group by。当与聚合方法一起完成时,通常是可以的,但否则它可能会变成许多数据库调用(一个用于获得键的不同值,然后每个值一个)。

考虑到以上内容(我省略了提及每一列)。如果不使用AsEnumerable()(或ToList()或其他什么),由于wcopy可能完全在查询之外(我看不出它是在哪里定义的),第一个生成的SQL将是(如果允许的话),类似于:

select startTime, count(id), max(timeInSession), /* ... */
from tasks
group by startTime

数据库应该非常有效地处理它(如果不是,请检查索引并对生成的查询运行数据库引擎优化顾问)。

不过,在内存中进行分组后,它可能会首先执行:

select distinct startTime from tasks

然后

select timeInSession, /* ... */
from tasks
where startTime = @p0

对于找到的每个不同的startTime,将其作为@p0传入。无论其余代码的效率如何,这都可能很快变成灾难性的。

我们有两个选择。哪一个最好因情况而异,所以我会同时给出,尽管第二个是最有效的。

有时,我们最好的方法是加载所有相关的行,并在内存中进行分组:

var statistics =
  from record in startTimes.AsEnumerable()
  group record by record.startTime
  into g
  select new e_activeSession
  {
    workerId = wcopy,
    startTime = g.Key.GetValueOrDefault(),
    totalTasks = g.Count(),
    totalTime = g.Max(o => o.record.timeInSession).GetValueOrDefault(),
    /* ... */
  };

我们可以通过只选择我们关心的列来提高效率(如果上面使用了表中的每一列,则无关紧要)

var statistics =
  from record in (
    from dbRec in startTimes
    select new {dbRec.startTime, dbRec.timeInSession, /*...*/}).AsEnumerable()
    group record by record.startTime
    into g
    select new e_activeSession
    {
      workerId = wcopy,
      startTime = g.Key.GetValueOrDefault(),
      totalTasks = g.Count(),
      totalTime = g.Max(o => o.record.timeInSession).GetValueOrDefault(),
      /* ... */
    };

不过,我认为这不是最好的情况。在我要枚举组,然后枚举每个组的情况下,我会使用这个。在您对每个组进行聚合而不枚举的情况下,最好将聚合工作保存在数据库中。数据库在这方面做得很好,它将大大减少通过网络发送的数据总量。在这种情况下,我能想到的最好的办法是强制一个新对象,而不是镜像它的实体类型,但它没有被识别为实体。你可以为此创建一个类型(如果你正在做几个变体,这很有用),否则只使用匿名类型:

var statistics = (
  from record in startTimes
  group record by record.startTime
  into g
  select new{
    startTime = g.Key.GetValueOrDefault(),
    totalTasks = g.Count(),
    totalTime = g.Max(o => o.record.timeInSession).GetValueOrDefault(),
    /* ... */
  }).AsEnumerable().Select(
    d => new e_activeSession
    {
      workerId = wcopy,
      startTime = d.startTime,
      totalTasks = d.totalTasks,
      /* ... */
    });

明显的缺点是过于冗长。然而,它将保持在数据库中最好的操作,同时仍然不会像ToList()那样浪费时间和内存,不会重复命中数据库,并将e_activeSession创建从linq2sql拖到linq2objects中,因此应该允许这样做。

(顺便说一句,.NET中的约定是类和成员名称以大写字母开头。这没有技术原因,但这样做意味着你将匹配更多人的代码,包括BCL和你使用的其他库的代码)。

编辑:顺便提一下,第二次;我刚刚看到你的另一个问题。请注意,在某种程度上,这里的AsEnumerable()是导致该问题的确切原因的变体。仔细想想,你会发现很多关于不同linq查询提供程序之间边界的问题。