Migrate a Sql query to EF linq
Migrate a Sql query to EF linq
February 25, 2019
If you are like me, you write queries in SQL and you use Dapper (or some other cool ORM) to connect to your database, run your queries and you are as happy as a clam.
Sometimes, however, you get to a point where doing what you've always done, just isn't cool anymore. Let's say, for example, that you want to work with EF and code first, well, it would go a little bit against the flow to tell your peeps, well, the EF Framework/Code First thing is cool, but I want to use Dapper. Now you've become un-cool ...
So for the few of us that need to understand how to build a join in EF Linq, I give you this tutorial.
Writing in Linq
Let's start by writing the query we want.
select t1.*, t2.*, (t1.Value1 - t2.value2) as CalculatedValue
from Table1 t1 join Table2 on t1.table2_id = t2.id
where CalculatedValue > 1000
This is a very simple query but caused me great pains to try to write in Linq.
First off you need to make sure you have all the correct using statements.
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
Now that we have this figured out, let's look at the Linq query:
var recommendations =
this.dbContext.Table1
.Join( this.dbContext.Table2,
t1 => t1.table2_id,
t2 => t2.id,
(t1, t2) => new
{ Table1 = t1,
Table2 = t2,
CalculatedValue = t1.Value1 - t2.value2
} )
.Where(x => x.CalculatedValue > 1000)
.ToList();
All of this may be obvious to some of you but it took me a minute for it to click.
Let's try to do this in words:
Table1.Join(tableToJoin, table1OnParameter, table2OnParameter, ObjectThatRepresentsTheSelect).Where(WhereStatement) ..
A little more details:
This:
from table1 join table1 on t1.table2_id = t2.id
Translates to
Table1.Join( this.dbContext.Table2, t1 => t1.table2_id, t2 => t2.id,
Are you starting to see it now?
So this:
select t1.*, t2.*, (t1.Value1 - t2.value2) as CalculatedValue
Translates to this
(t1, t2) => new { Table1 = t1, Table2 = t2, CalculatedValue = t1.Value1 - t2.value2 }
I know you are seeing it.
So it took a while an the syntax may be counter intuitive but once you understand at least this part, you can start writing complex queries using Linq. Just be careful to inspect the query before you deploy just in case it's not optimized.
Now you go out there and enjoy your Entity Framework Linq queries ... ;)