Skip to content

LINQ and Joined Tables

by dotnetdave on April 23rd, 2009

Introduction

I have had an introduction into the world of LINQ today. I have been aware of LINQ for some time but today was the first day that I have had to use it to do some real world queries. I wanted to do a standard joined table selection. the SQL would have been somthing like:

SELECT * FROM table1 INNER JOIN table2 ON table1.ID = table2.FKID WHERE table1.ID = @ID

LINQ

The LINQ to Entities method of performing this join has proved hard to find but I found a helpful post on a MSDN Forum that pointed me in the right direction.

Entities db = new Entities();
int Id = 4; //Hardcoded for example
var result = db.Entity1.Where(e => e.Entity2.Any(f => f.ID == Id));

The result of this joined query was the Entity1 rows where the joining table connected it to Entity2. Result

Hope this helps!

From → ASP.Net

3 Comments
  1. Eily permalink

    Sweet tutorial dave! Keep up the posts!

  2. Kevin Sparrow permalink

    Hi Dave, we’ve been doing a lot with EF recently so if you need any code shout.

  3. Dave permalink

    Thanks Kev I will take you up on that soon.

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS