2011-03-20 54 views
0

我有這樣的一個表:問題與DISTINCT和LINQ2SQL

idinterpretation | iddictionary | idword | meaning 
1     1    1115  hello 
2     1    1115  hi 
3     1    1115  hi, bro 
5     1    1118  good bye 
6     1    1118  bye-bye 
7     2    1119  yes 
8     2    1119  yeah 
9     2    1119  all rigth 

,我要儘量讓不同行(DISTINCT idword)。所以,起初我嘗試過:

return dc.interpretations.Where(i => i.iddictionary == iddict). 
    ToList<interpretation>().Distinct(new WordsInDictionaryDistinct()). 
    OrderBy(w => w.word.word1).Skip(iSkip).Take(iTake); 

但我在我的表中有大約300.000行,這是錯誤的解決方案。

然後,我想:

IEnumerable<interpretation> res = (from interp in dc.interpretations 
             group interp by interp.idword into groupedres 
             select new interpretation 
             { 
              idword = groupedres.Key, 
              idinterpretation = groupedres.SingleOrDefault(i => i.idword == groupedres.Key).idinterpretation, 
              interpretation1 = groupedres.SingleOrDefault(i => i.idword == groupedres.Key).interpretation1, 
              iddictionary = groupedres.SingleOrDefault(i => i.idword == groupedres.Key).iddictionary 
             }).Skip(iSkip).Take(iTake); 

,我把錯誤:@foreach (interpretation interp in ViewBag.Interps)System.NotSupportedException: Explicit construction of entity type 'vslovare.Models.interpretation' in query is not allowed.

,這真是個方式,採取不同的列,並在完成行這樣的有:

idinterpretation | iddictionary | idword | meaning 
1     1    1115  hello 
5     1    1118  good bye 
7     2    1119  yes 


詞典:

dictionary table 

iddictionary | dictionary_name 

話:

word table 

idword | word_name 

解釋:

interpretation table 

idinterpretation | iddictionary | idword | meaning 
+1

在第一個代碼段,爲什麼之前含混做一個ToList? ToList將導致所有未被Where從數據庫中拉下來的記錄。 – rsbarro 2011-03-20 15:35:36

+0

因爲。凡(I => i.iddictionary == iddict).Distinct(新WordsInDictionaryDistinct())得到一個更錯誤:System.NotSupportedException:用於查詢運算符 '獨特' 不支持的過載。 – FSou1 2011-03-20 15:45:29

+0

我認爲這是因爲對Distinct的調用中有新的WordsInDictionaryDistinct()。這應該是一個IEqualityComparer。你可以將WordsInDictionaryDistinct的實現添加到問題中嗎? – rsbarro 2011-03-20 15:52:48

回答

2

我覺得你的第二次嘗試幾乎沒有 - 你可能需要使用的GroupBy條款來得到這個工作在SQL中。

喜歡的東西:

var query = from row in dc.interpretations 
      where row.iddictionary == iddict 
      group row by idword into grouped 
      select grouped.FirstOrDefault(); 

return query.OrderBy(w => w.word.word1).Skip(iSkip).Take(iTake); 

爲什麼您的查詢的時間過長 - 在一般情況下,如果您的查詢速度慢那是因爲你正在尋找和返回的數據是真正的大 - 或因爲它在數據庫級別索引不佳。爲了找出答案,它正在分析或剖析您的查詢 - 看到這篇文章在MSDN上http://msdn.microsoft.com/en-us/magazine/cc163749.aspx

+0

所以,我應該怎麼投AnonymousType到了IEnumerable <解讀>或返回AnonymousType? – FSou1 2011-03-20 16:37:06

+0

我認爲在我的答案中的查詢應該返回一個IQueryable - 添加ToList()以實際調用查詢到一個IEnumerable (實際上是一個IList Stuart 2011-03-20 16:41:38

+0

是的,它確實工作。Thx :) – FSou1 2011-03-20 16:48:33