Reputation: 1
I am trying to put a Where Clause in reading a SQL server database table where some conditions are depending on other variables, I have 7 fields to do the filtering in the database and are entered by the user , anyone can have a value or can be null . it should look like this if all search variables Var1, etc are not null
Select * from Table1 where Field1 = var1 and Field2 = Var2 and Field3 = Var3
However if Var2 for example is null it should be ignored in the Select statement and it will look like
Select * from Table1 where Field1 = var1 and Field3 = Var3
It's much like SQL string, however when using the select statement with Lambda expression as in Entity Framework, I could not find any thing like simple sql string .
I am using VS2017 with c# coding language for an ASP.NET Core application. Database server is SQL2016 .
This looks pretty much standard, however, I could not find a solution. Does anyone have a good solution?
Upvotes: 0
Views: 1207
Reputation: 14261
If I understand correctly what you want, the standard way is this:
using (var context = new SomeContext())
{
IQueryable<SomeEntity> query = context.SomeEntities;
if (var1 != null)
query = query.Where(x => x.Field1 == var1);
if (var2 != null)
query = query.Where(x => x.Field2 == var2);
// and so on
// use the query somehow
}
Upvotes: 2