I barely work with raw SQL since I use EF most of the time (so I might have misinterpreted some of the commands) and neither did I have the time to test the second query so I appologize in advance if there are any mistakes.
First SQL query translated:
var result = hastaliklars.GroupBy(hastaliklar => hastaliklar.HastalikIsmi)
.Select(hastaliklarGroup =>
(HastalikIsmi: hastaliklarGroup.Key, Count: hastaliklarGroup.Count()))
.OrderByDescending(hastalikIsmiWithCount => hastalikIsmiWithCount.Count)
.Take(3)
.ToList();
Second SQL query translated:
var result2 = calisanlars.Join(hastaliklars,
calisanlar => calisanlar.CalisanId,
hastaliklar => hastaliklar.CalisanId,
(calisanlar, hastaliklar) =>
(Calisanlar: calisanlar, Hastaliklar: hastaliklar))
.Where(calisanlarAndHastaliklar => hastaliklars
.GroupBy(hastaliklar => hastaliklar.HastalikIsmi)
.OrderByDescending(hastaliklarGroup => hastaliklarGroup.Count())
.Take(3)
.Any(hastaliklarGroup =>
calisanlarAndHastaliklar.Hastaliklar.HastalikIsmi == hastaliklarGroup.Key))
.ToList();
Note that if you're working with an IQueryable<T>
instead of an IEnumerable<T>
you might get a runtime exception stating that the LINQ expression could not be translated and will be evaluated locally. The reason why this might happen is because an IQueryable<T>
is not run locally on C# but rather just contains instructions on what you're trying to do and translates that into an SQL query string. Therefore, specific code can not be translated into SQL which causes this exception.
The easiest way to fix this would be to run the method AsEnumerable()
before the method which can not be translated to SQL which forces only all of the previous instructions to be run via SQL and then reads and works with the results locally from there on out. However, it does come at a performance cost, so that it would be slower than running the entire query via SQL. Therefore the optimal solution would be to adjust the code so that all of it could be translated into SQL if possible.
I don't fully remember what code IQueryable<T>
supports and what not but as a good start; Here's a link to the microsoft docs that lists all of the LinQ functions it supports: https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/ef/language-reference/supported-and-unsupported-linq-methods-linq-to-entities?redirectedfrom=MSDN