2011-03-20 63 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