Customized ( Where) clause in Entity Framework

asp.net-core c# entity-framework-core

Question

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?

1
0
7/14/2019 2:42:48 AM

Popular Answer

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
}
2
7/7/2019 1:45:22 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow