0

I am somewhat new to EF and .NET Core. I'm coming from the PHP Framework Laravel which have some similar logic for Models and Query building, but I can't seem to find the relevant documentation for what Im looking for.

I have a Model where I want to perform a query based on POST data from a form, and filter the outcome based on the input from the user.

In Laravel I was able to do this conditionally to build a query for a Model like so:

$projects = Project::when($request->year_from, function($query) use ($request){
    $query->where('delivery_year', '>=', $request->year_from);
})
->when($request->year_to, function($query) use ($request){
    $query->where('delivery_year', '<=', $request->year_to);
})->get();

Here I added where statements to the query if the request contained any data for that specific filter. Is there a similar solution to Query models in EF?

I started writing some code like this, but I clearly realized it to be a bad implementation, since I start by fetching the entire result set, before eliminating results:

var logs = context.Logs.All();

if( PostData.LogLevel != null )
{
    var logs = logs.Where((log) => log.LogLevel == PostData.LogLevel);
}
Ole Haugset
  • 3,709
  • 3
  • 23
  • 44
  • You need to store a reference to your collection as `IQueryable`. See duplicate. – CodeCaster Sep 03 '18 at 09:39
  • you can do the following `var query = context.Set() if(bool == true){ query = query,Where(s=>s.MyCondition); } var data = query.ToListAsync(); ` – JB's Sep 03 '18 at 09:47

1 Answers1

3

Edit : I just made a stupid mistake . I've updated my code , thanks to @CodeCaster .

var logs = context.Log;

IQueryable<Log> q = null
if( PostData.LogLevel != null )
{
   q = logs.Where(log => log.LogLevel == PostData.LogLevel);
}
if( ... ){
   q = q.Where() ; 
}
// ... 

...

var list=await q.ToListAsync();

LINQ is lazy , which means we just define the expression tree that will be executed in future . Think about a lambda function in PHP which will not execute until we invoke it explicitly . The code above will not be executed until the last line ToListAsync()

itminus
  • 23,772
  • 2
  • 53
  • 88