7

So, I've been trying to replicate this SQL query:

select COUNT(*) as Total_2_Review from ( select processed_image_id, count(*) as Total_Confirm from dbo.history where action_id=104 group by processed_image_id having count(*) > 1 ) as tbl 

with Linq as follows:

var total2Review = (from h in secondDb.Histories.Where(i => i.ActionId == 104) group h by new { h.ActionId, h.ProcessedImageId } into g where g.Key.ActionId > 1 select g).Count(); 

However, I know it should not be right because I am not selecting the actual count greater to 1 in my group clause.

How can I accomplish this SQL query as a LINQ query?

1
  • Why are you grouping by ActionId in the Linq when you aren't in the SQL? Commented Nov 25, 2015 at 16:00

2 Answers 2

10

LINQ makes no difference between Where and Having. An appropriate SQL query would be generated based on your placement of the Where clause.

Here is how I would translate your SQL query to LINQ:

var total2Review = secondDb.Histories .Where(i => i.ActionId == 104) // This "Where" remains a "where" .GroupBy(i => i.ProcessedImageId) .Where(g => g.Count() > 1) // This "Where" becomes "having" .Count(); // This gets the overall count 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the explanation
Can you help me how to get Count on a datefield? I have some student data with their exam dates. I wanna count the dates where the count is greater than two. Date field doesnt have a date.Count()?
7

Change Key.ActionId for .Count() in the where after the group by:

var total2Review = (from h in secondDb.Histories.Where(i => i.ActionId == 104) group h by new { h.ActionId, h.ProcessedImageId } into g where g.Count()> 1 select g).Count(); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.