2

Here is my LINQ query that needs to update to dynamic where clause. If parameter's id value is 0 then where clause should return all records else where clause should match records as per id value.

public async Task<IEnumerable<dynamic>> GetFilteredRowsByID(int id)
        {
            return from m in _context.TableName
                   where m.id == (id != 0 ? id : /*AllRecordsHere*/ )
                   join ...
                   join ...
                   select new {...}
        }

I use Asp.Net Core 2.2. Is it possible without writing another method witout where clause for this?

2
  • try this, where (id != 0 && m.id == id) || true
    – Peter-Yu
    Sep 11, 2019 at 5:26
  • Look at Expression type Sep 11, 2019 at 5:27

4 Answers 4

4

I will use AsQueryable lazy query instead of one LINQ Query to do it. because it's more readable i think.


    var query = (from m in _context.TableName.AsQueryable() select m );
    if(id != 0)
        query = query.Where(w=>w.id == id);
    query = ( from m in query
        join ...
        join ...
        select new {..}
    )

0
3

Try condition:

where id == 0 || m.id == id

in case when id == 0, whole expression evaluates to true, otherwise it is false and second condition m.id == id would be checked.

1
  • Meanwhile this method is correct, the conversion to SQL of a large number of this conditions can result in a lot of CASE-WHEN syntax that can destroy the improvement really quick if the data is not well allocated. Be aware using this method if you are not working with lazy linq Dec 30, 2021 at 17:55
2

I'm not sure that you can achieve this cleanly with 100% expression syntax, but you can with fluent syntax:

var result = _context.TableName;
if (id != 0) result = result.Where(m => m.Id == id);
result = result.Join(...).Join(...).Select(m => m.new {...});

A key benefit of fluent syntax is that it simplifies query composition.

You can freely mix expression and fluent syntax.

1

Move id != 0 ? outside of the equals expression:

public async Task<IEnumerable<dynamic>> GetFilteredRowsByID(int id)
{
    return from m in _context.TableName
           where id != 0 ? m.id == id : true
           join ...
           join ...
           select new {...}
}

Hopefully EF would be able to optimize the where true to remove the condition entirely.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.