Dynamic Queries using LINQ Expressions

Lambda expressions are very common when using Entity Framework to query a SQL database.

And on most occasions, writing a lambda expression directly is fine.

The problem comes if you want to use the same expression, but pass in different objects or properties into it.

It's not possible to do this directly in code.

This is where LINQ expressions comes in.

LINQ expressions allows you to build up each part of the LINQ expression, bit by bit.

And once you are happy with your expression, it can be converted into a Lambda expression.

Once it's a lambda expression, it can be used in Entity Framework.

Software

This is the software that will need to be installed onto your machine.

Get The Application Working

These are the steps to get the application working.

  • Fill out the Download the Source Code form. We will send you an email where you can download the source code.
  • Inside the source code, there is a folder called Database. Within that folder, there is a file called LinqExpressions-Example.bak. This needs to be imported as a database into your SQL Server.

From there, you will need to open up the RoundTheCode.LinqExpressions-Example/appsettings.json file and change this setting:

  • Check the database connection is correct in ConnectionStrings > LinqExpressionsDbContext.

You are now ready to go.

Open the Project in Visual Studio

Open up RoundTheCode.LinqExpressions-Example.sln in Visual Studio. Make sure that the project RoundTheCode.LinqExpressions-Example is set as the start up project.

You should find that the web application runs on https://localhost:8000.

Start the project in Visual Studio.

Open up a browser and navigate to https://localhost:8000.

You should now have your dynamically queries being displayed on the screen.

You can see the code to where this is happening by going to the RoundTheCode.LinqExpressions-Example/Controllers/HomeController.cs file.

More Information

You can read our Using LINQ expressions to build dynamic queries in Entity Framework article for more information on this subject.

Join our Discord server

  • Can't get your ASP.NET Core application to work? Ask for help here!
  • Discussions with other ASP.NET Core developers.
  • General chat with the community.
Join Discord