LINQ版本的SQL查询

时间:2012-04-19 06:30:03

标签: sql-server linq entity-framework linq-to-sql tagging

我有以下表格:

Monster:  
Name     Description              EatsPeople 
Vampire  Pale, afraid of light    True 
Ghost    See-through, annoying    False 
Wraith   Green-ish, ugly, dumb    True 

TagLookup: 
Name    ID 
Ghost   1 
Ghost   2 
Wraith  1 

Tags: 
ID    Text                      Value 
1     Green                     green-skin 
2     Screams like a banshee    banshee-call 

要查询具有绿皮标记的怪物,我使用此SQL查询:

SELECT m.Name, m.Description, m.EatsPeople 
  FROM dbo.Monster AS m 
  INNER JOIN dbo.TagLookup AS tl 
    ON m.Name = tl.Name 
  INNER JOIN dbo.Tags AS t 
    ON t.ID = tl.ID 
    AND t.Value = 'green-skin'; 

这正如您所期望的那样工作得很好,但是我遇到了这个查询的LINQ版本的问题。我试过LinqPad没有运气+搜索Bing + Stackoverflow没有太多运气

2 个答案:

答案 0 :(得分:1)

这将产生相同的join

var result=(
    from m in db.Moster
    join tl in db.TagLookup
        on tl.Name equals tl.Name
    from t in db.Tags.Where(x=>x.ID==tl.ID && x.Value = "green-skin")
    select new
    {
        m.Name, 
        m.Description, 
        m.EatsPeople 
    });

或者你也可以这样做。这将产生相同的结果:

var result=(
    from m in db.Moster
    join tl in db.TagLookup
        on tl.Name equals tl.Name
    join t in db.Tags
        on tl.ID equals t.ID
    where
        t.Value = "green-skin"
    select new
    {
        m.Name, 
        m.Description, 
        m.EatsPeople 
    });

答案 1 :(得分:0)

试试这个:

 var a = from m in Monsters
            join tl in TagLookup  
                on m.Name equals tl.Name  
            join t in Tags
                on t.ID = tl.ID  
            where t.Value = 'green-skin';
            select new 
            {
                 m.Name, 
                 m.Description, 
                 m.EatsPeople  
            };