Ask Your Question
0

How to write an EF Core Linq Query that chooses two columns from a different table?

asked 2023-04-29 21:32:53 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-04-29 21:39:01 +0000

woof gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-04-29 21:32:53 +0000

Seen: 9 times

Last updated: Apr 29 '23