Implement Joins in EntityFramewok Using DB Context and LINQ

Excerpts from MSDN about LINQ

Language-Integrated Query (LINQ) is a set of features introduced in Visual Studio 2008 that extends powerful query capabilities to the language syntax of C# and Visual Basic. LINQ introduces standard, easily-learned patterns for querying and updating data, and the technology can be extended to support potentially any kind of data store. Visual Studio includes LINQ provider assemblies that enable the use of LINQ with .NET Framework collections, SQL Server databases, ADO.NET Datasets, and XML documents.

In this article I am sharing how to use joins in Entity Framework with a DB context and a LINQ query.

I will use a sample application to demonstrate this feature.

We need to create DB Context object to understand the fact and advantages, so let's create a .edmx and dig into more details. Kindly follow the following procedure to create a DBContext. Create a sample MVC application and follow the procedure below.

1. Right-click on the Model folder and proceed as shown in the following screenshot:

Linq.jpg

Choose "Visual C#" => "ADO.NET Entity Data Model" then provide the name as you need to (for exampleNorthwind.edmx) as in the following:

Linq1.jpg

Click "Add" then a new window will appear as in the following:

Linq2.jpg

Select "Generate from database" and click "Next"; the following window will appear:

Linq3.jpg

Click on "New Connection" and fill in the required details as shown in the following image to connect with the server (in this for example I have used "local DB Server").

Linq4.jpg

Click on "Test Connection" to verify that the connection has been established.

Linq5.jpg

Click "Ok" and proceed further.

Linq6.jpg

Click "Next", the following window will appear:

Linq7.jpg

Select the required database objects as per your needs and click on the "Finish" button.

An edmx file will be added into the solution as per the image show under the following:

Linq8.jpg

These are the very basic steps to create an entity object from an existing database as shown above. Now let's proceed further and get to the core topic to use Joins with Entity Framework.

Now open the RegisterController class file and write my code in Action "Verify" also as shown in the following image:

Linq9.jpg

You can see the code snippet in the above diagram states that we are using an inner join on two tables, Orders and OrderDetails, and return the result to the view (that is of type OrderModel having the following code snippet).

Linq10.jpg

Now I run the sample application and press F5.

Linq11.jpg

It's very simple in use, we just need to understand how to implement this. Hope it will be helpful somewhere someday. And I will contimue to post a few more articles related to MVC, Entity and many more.

A sample application is attached as a reference.

Hope you enjoyed this demonstration

Keep coding and Be Happy.


Similar Articles