简体   繁体   中英

Place if statement inside a where clause in Linq for Entity framework

take the following.

       var query = context.Fields
            .Where( 
                x => x.DeletedAt == null 
            );

        // Apply search
        if( searchCriteria != null )
        {
            if( searchCriteria.SearchTerm != "" )
            {
                query.Where(
                    x => x.Location.Contains( searchCriteria.SearchTerm )
                );
            }
        }

this won't work because there are two where statements, they do not join up.

How would i do this statement? It might look like this:

var query = context.Fields
            .Where( 
                x => x.DeletedAt == null &&
                {
                    if( searchCriteria != null )
                    {
                        if( searchCriteria.SearchTerm != "" )
                        {
                            return x.Location.Contains( searchCriteria.SearchTerm );
                        }
                    }
                }
            );

What is wrong with the following:

    var query = context.Fields
        .Where( 
            x => x.DeletedAt == null 
        );

    // Apply search
    if( searchCriteria != null )
    {
        if( searchCriteria.SearchTerm != "" )
        {
            query = query.Where(
                x => x.Location.Contains( searchCriteria.SearchTerm )
            );
        }
    }
    return query;

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