我已經閱讀了幾個關於「不允許在查詢中顯式構造實體類型」的錯誤問題,以及解決它的各種方法。使用LINQ插入/選擇 - 在查詢中獲取實體構造
- Explicit construction of entity type '###' in query is not allowed.
- Explicit construction of entity type [MyClass] in query is not allowed
- Explicit construction of entity type '' in query is not allowed
我使用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
似乎效率非常低,只是讓我的代碼在那裏呆了很長時間。有一個更好的方法嗎?
感謝您的非常詳細的答案,並解釋LINQ如何轉換爲SQL。 「AsEnumerable」真的加快了速度。我喜歡你的最後一個版本,因爲即使它是冗長的,它似乎讓我把SQL中的計算(聚合)與C#中的計算分開。最後,關於大寫:e_activeSession是表名中自動生成的類。 我現在有一些奇怪的'InvalidCastException'錯誤,但我將另存一天。 – 2012-08-04 02:12:02
這裏一個非常有用的東西是運行SQL Profiler,特別是在你學習它的時候。大多數情況下,生成的SQL將與您預期的非常相似。有時甚至可能會更好(Linq在引入APPLY之前沒有多年的SQL經驗,所以它在我不想的時候「認爲」APPLY,但「APPLY」是最好的方法)。在極少數情況下,你會看到它做了一些可怕的事情,然後你想看看你的Linq查詢,並考慮它爲什麼會這樣做(比如當它將一個'group'變成一千個獨立的調用時)。 – 2012-08-04 08:45:07