Entity Framework Core search string for model

1.2k Views Asked by At

I use ASP.NET Core 3 with Entity Framework Core. I have problems to implement a search string for one of my models.

My controller method is the following:

public async Task<IActionResult> IndexPartial(string? searchValue)
{
   IQueryable<Student> query = _context.Students;
   query = (searchString == null)? query : query.Where(s => s.FullName.Contains(searchValue));
   return PartialView(await query.ToListAsync());
}

My model class does not store FullName in the database, only FirstName and LastName.

public class Student
{
    public int Id {get; set;}
    public string FirstName {get;set;}
    public string LastName {get;set;}

    public string FullName => FirstName+" "+LastName;
}

Do I have to filter the table client-side, or is there a workaround using LINQ?

1

There are 1 best solutions below

0
On BEST ANSWER

I found a workarround. Just change the controller method like this:

public async Task<IActionResult> IndexPartial(string? searchValue)
{
    IQueryable<Student> query = _context.Students;
    var list = await query.ToListAsync();
    list = (searchString == null)? list : list.FindAll(s => s.FullName.Contains(searchValue));
    return PartialView(await list);
}

I think when you modify the IQueryable, you can only use Model Properties that are saved in the Database Table created by Entity Framework, because manipulating the query is done with SQL.