将SQL查询转换为Linq

时间:2013-11-12 12:46:18

标签: c# sql linq entity-framework

我想将此查询转换为LINQ / EF

select a.ArticleId, COUNT(*) as total from Articles a
inner join MetaKeywords b on a.ArticleId = b.ArticleId 
where b.MetaKeyword in ('_catalog', '_register')
group by a.ArticleId
having COUNT(*) >= 2

我尝试了很多选项,但结果并不理想。

在上面的查询中,2是从子表中搜索的关键字数量。

2 个答案:

答案 0 :(得分:2)

试试这个:

var lst= new string[]{"_catalog","_register"};

var qry = (from a in db.Articles 
          join b MetaKeywords on a.ArticleId equals b.ArticleId
          where lst.Contains(b.MetaKeyword)
          group a by a.ArticleId into g
          where g.Count() >= 2
          select new {ArticleId = g.Key, Total = g.Count()} );

您应该注意lst在实际查询中声明

答案 1 :(得分:1)

使用方法链:

var list=new[]{"_catalog","_register"};
var result=Articles
    .Join(MetaKeyWords,t=>t.ArticleId,t=>t.ArticleId,(article,metakeywords)=>new{article,metakeywords})
    .Where(t=>list.Contains(t.metakeywords.MetaKeyword))
    .GroupBy(t=>t.article.ArticleId)
    .Select(t=>new{ ArticleId=t.Key,Total=t.Count()})
    .Where(t=>t.Total>=2);