0

I want to convert this query to 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..

7
  • 8
    "I tried many options but result was not as desired." => please post what you've tried. Commented Nov 12, 2013 at 12:47
  • Do you want to have this exact query translated to LINQ, or do you want a query that will "find all ArticleIDs that have some MetaKeyword duplicated" (like, more than one _register or more than one _catalog or more than one ...)? Commented Nov 12, 2013 at 12:49
  • stackoverflow.com/questions/530925/… Commented Nov 12, 2013 at 12:52
  • Try LINQPAd or LINQUER Commented Nov 12, 2013 at 12:54
  • Try using Codereview for questions like this. Commented Nov 12, 2013 at 12:55

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Much better (+1) but I think it is still pretty hard to read... syntax-wise. the Join always gets me lost :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.