Here are options to implement the same:
Option 1 : Using Dynamic LINQ Library
To implement the same you need to download Dynamic package library from Nuget. After downloading you need the methods defined in Dynamic Linq library. Here are some links that will help you:
http://weblogs.asp.net/scottgu/dynamic-linq-part-1-using-the-linq-dynamic-query-library[
^]
http://www.c-sharpcorner.com/UploadFile/deveshomar/dynamic-linq-library-in-C-Sharp/[
^]
Option 2 : Using Stored Procedure
This is another option to implement the same. Create a stored procedure(SP) and pass 3 params to procedure. In SP, implement your own logic to fetch data like if Category_ID greater than 0. Then execute the dynamic SQL.
Option 3 : Using Raw SQL
This is last option if you are not interested in above options - that is raw SQL. You need to generate raw SQL query as per requirement. Then execute raw SQL query through SqlQuery() method. Here is the code:
string query = "";
if(Category_ID > 0)
{
query += "Category_ID = " + Category_ID;
}
if(PriceFrom > 0)
{
if(query.Length > 0){
query += " AND PriceFrom = " + PriceFrom ;
}else{
query += "PriceFrom = " + PriceFrom;
}
}
if(PriceTo > 0)
{
if(query.Length > 0){
query += " AND PriceTo = " + PriceTo;
}else{
query += "PriceTo = " + PriceTo;
}
}
if(query.Length > 0){
query = "SELECT Name FROM tbl_Books WHERE " + query;
}else{
query = "SELECT Name FROM tbl_Books";
}
using (var context = new BooksEntities())
{
var bookNames = context.Database.SqlQuery<bookentity>(query).ToList();
}
Here
BookEntity is entity, you need to change as per your need. One disadvantage in this option is SQL vulnerability. Make sure that incoming data is correct so that it won't affect your Database.