简体   繁体   中英

Customized ( Where) clause in Entity Framework

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?

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM