0

I want to write the following SQL (MYSQL) query in C# (LINQ):

select m.Id, m.Title, sum(pow(cur.Rating,1.7))/count(cur.Rating) from Movies m
join MovieCategories mc on mc.MovieId = m.Id
join CategoryUserRatings cur on cur.CategoryId = mc.CategoryId
group by m.Id having min(cur.Rating) > 0 and count(cur.Rating) > 3
order by sum(pow(cur.Rating,1.7))/count(cur.Rating) desc;

Here is what I have:

from m in _dbContext.Movies
join mc in _dbContext.MovieCategories on m.Id equals mc.MovieId
join cur in _dbContext.CategoryUserRatings on mc.CategoryId equals cur.CategoryId
group new { m, cur } by m.Id into mcur
where mcur.Count() > 3 && mcur.Min(p => p.cur.Rating) > 0
let rating = mcur.Sum(s => Math.Pow(s.cur.Rating, 1.7)) / mcur.Count()
let movie = mcur.First().m
orderby rating descending
select new TestModel {Title = movie.Title, Rating = rating ...}

It works, but most of the grouping and aggregating is running locally see:

Warning: The LINQ expression 'GroupBy([m].Id, new <>f__AnonymousType2`2(m = [m], cur = [cur]))' could not be translated and will be evaluated locally.
Warning: The LINQ expression 'Count()' could not be translated and will be evaluated locally.
Warning: The LINQ expression 'Min()' could not be translated and will be evaluated locally.
…

So basically what I want is to join 3 tables together and then Group by the MovieId so I get something like this:

MovieId, Title, SUM Rating, [...]
1,       Test,  77
2,       Test2, 66
3,       Test3, 55

Is there a way to do this with C# / LINQ without running it locally or should I just create a view?

3
  • Are you using EF Core? You need the latest version to have GroupBy translated to SQL.
    – NetMage
    Nov 12, 2018 at 17:16
  • Yep I'm using 2.2.0 Preview2
    – FromThe
    Nov 12, 2018 at 18:08
  • Looks GroupBy with aggregation isn't translated by EF Core: github.com/aspnet/EntityFrameworkCore/issues/11813; also I don't think EF Core intends you to use explicit joins.
    – NetMage
    Nov 12, 2018 at 18:35

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.