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

标签 c# sql linq select

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

我在我的代码中使用 DBML 自动生成的 LINQ to 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 似乎效率低得令人难以置信,只会让我的代码在那里停留很长时间。有更好的方法吗?

最佳答案

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

通常,除非您真的想要一个列表(例如,如果您会多次访问相同的数据,因此该列表充当缓存)。

到目前为止我们有:

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 查询提供程序之间的界限。

关于c# - 使用 LINQ 插入/选择 - 绕过查询中的实体构造,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11804833/

相关文章:

c# - 如何执行给定次数的while循环?

python - 如何使用 django 删除图像?

c# - 在 C# 中使用参数化查询时抛出异常

c# - 行动 lambda 中的逆变 - C#

c# - 在 C# 中是否有更简单的方法为函数指定别名

sql - 创建 SQL View 时如何从日期时间获取日期?

c# - 将一本字典转换成另一本字典的最佳方法是什么

c# - 如何使用 linq to xml 创建多态数组?

c# - 在 LINQ-to-SQL 中使用跨上下文连接

c# - Ajax 调用在物理上不同的文件中对 Controller 较慢