Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Assuming you have two tables with a foreign key relationship - Table1 and Table2, and you want to select two columns from Table2, you can use a join in your EF Core Linq query as follows:

var result = context.Table1
                .Join(context.Table2,
                      t1 => t1.Table2Id,
                      t2 => t2.Id,
                      (t1, t2) => new { Column1 = t1.Column1, Column2 = t2.Column2})
                      .ToList();

In this query, we first utilize the Join method to join the two tables on their foreign key relationship. We then select two columns from Table2 i.e Column2 and join them with Column1 from Table1.

The Join method takes four arguments - the first argument is the inner table that we want to join, the second argument is the foreign key property in Table1 that we want to join with, the third argument is the primary key property in Table2 that we want to join with, and the fourth argument is a projection that specifies what columns/values we want to select from the join. In this case, we want to select Column1 from Table1 and Column2 from Table2.

We then call the ToList() method to materialize the results into a list.

Note that the result is an anonymous object because we projected two columns from different tables. If you wanted to select all columns from one or both tables, you could replace the anonymous object with a concrete class that has the desired properties.