将sql查询写入linq

时间:2013-04-14 18:33:18

标签: c# sql linq

我在sql中有以下查询:

SELECT [definition],[pos]
  FROM [WordNet].[dbo].[synsets]
  where synsetid in(SELECT [synsetid] FROM [WordNet].[dbo].[senses] 
  where wordid = (select [wordid]FROM [WordNet].[dbo].[words]
  where lemma = 'searchString'))

我曾尝试过将sql转换为linq:

long x = 0;

if (!String.IsNullOrEmpty(searchString))
{
    var word = from w in db.words
               where w.lemma == searchString
               select w.wordId;
    x = word.First();

   var sence = from s in db.senses
               where (s.senseId == x)
               select s;
   var synset = from syn in db.synsets
                where sence.Contains(syn.synsetId)
                select syn;

但我在sence.Contains()

时遇到以下错误
  Error1:Instance argument: cannot convert from
  'System.Linq.IQueryable<WordNetFinal.Models.sense>' to
  'System.Linq.ParallelQuery<int>'  

3 个答案:

答案 0 :(得分:2)

代码如下:

var sence = from s in db.senses
               where (s.senseId == x)
               select s;

返回类型为WordNetFinal.Models.sense的对象,但在where sence.Contains(syn.synsetId)中,您尝试在其中搜索syn.synsetId这是一个整数。

所以你应该将上面的代码更改为:

var sence = from s in db.senses
                   where (s.senseId == x)
                   select s.senseId;

答案 1 :(得分:0)

x似乎是Word类型,它不是Id的类型(可能是int或long)。

答案 2 :(得分:0)

您将整个sense行与synsetId进行比较,这是不正确的。您还使用First()将原始查询拆分为两个单独的查询,这会触发到目前为止对表达式的求值。如果words中存在重复项,则可以不返回SQL错误,您可以将查询写成这样的内容;

if (!String.IsNullOrEmpty(searchString))
{
    var wordIds = from word in db.words
                  where word.lemma == searchString
                  select word.wordId;

    var synsetIds = from sense in db.senses
                    where wordIds.Contains(sense.wordId)
                    select sense.synsetId;

    var result = (from synset in db.synsets
                  where synsetIds.Contains(synset.synsetId)
                  select new {synset.definition, synset.pos}).ToList(); 
}

ToList()为整个查询触发一次评估。

您也可以使用更简单的连接来完成;

var result = (from synset in db.synsets
              join sense in db.senses on synset.synsetId equals sense.synsetId
              join word in db.words on sense.wordId equals word.wordId
              select new {synset.definition, synset.pos}).ToList();