我已经阅读了几个关于“不允许在查询中显式构造实体类型”错误的问题,以及解决它的各种方法。
我在我的代码中使用 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
似乎是非常低效的,只是让我的代码在那里呆了很长时间。有一个更好的方法吗?