简体   繁体   English

将SQL查询转换为Linq

[英]Converting SQL query to Linq

I want to convert this query to LINQ / EF 我想将此查询转换为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

I tried many options but result was not as desired. 我尝试了许多选项,但结果并不理想。

In the above query 2 is number of keywords to searched from child table.. 在上面的查询2中是要从子表中搜索的关键字数。

try this: 尝试这个:

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()} );

You should note that the lst is declared outside the actual query. 您应该注意, lst是在实际查询之外声明的。

Using method chaining: 使用方法链接:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM