LINQ Expression Could not Be Translated

Kmcnet 696 Reputation points
2022-10-28T19:13:58.377+00:00

Hello everyone and thanks for the help in advance. I am creating a MVC application uisng .Net 6 and EF 6 to query a database. One of the functions is needed to search a date of birth. However, when I attempt to use the following:

persons = ctx.person.Where(x => (x.dateofbirth.ToString().Contains(searchTerm))).ToList();  

The searchTerm is sent via ajax query and is in the format mm/dd/yyyy. The preference is when mm/dd is input, the list of potential matches is returned to the autocomplete input. I have tried escaping the "/" separators by

searchTerm = searchTerm.Replace("/", @"\/");  

However the error persists. I'm not sure where to go form her. Any help would be appreciated.

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
698 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,288 questions
0 comments No comments
{count} votes

Accepted answer
  1. AgaveJoe 26,146 Reputation points
    2022-10-28T21:13:58.41+00:00

    Take advantage of MVC model binding when passing data to a controller.

    [HttpGet]  
    public IActionResult Index(DateTime birthday)  
    {  
        List<Person> people = _context.Persons.Where(p => p.Birthday == birthday).ToList();  
        return Ok(people);  
    }  
    

    The model.

        public class Person  
        {  
            public int Id { get; set; }   
            public string Name { get; set; } = string.Empty;  
            public DateTime Birthday { get; set; }  
        }  
    

    The URL is simply.

    https://localhost:7141/person/?birthday=1/1/2022  
    

    The example I provided is a GET but a post works exactly the same way. See any MVC tutorial and the model binding documentation.

    ASP.NET Core MVC with EF Core - tutorial series
    Model Binding in ASP.NET Core

    Lastly, when asking for assistance please post enough code to reproduce the actual issue. There could be other issues with your approach that we cannot see.


1 additional answer

Sort by: Most helpful
  1. Kmcnet 696 Reputation points
    2022-10-29T14:33:45.523+00:00

    Changing my original code to:

    persons = ctx.person.Where(x => (x.dateofbirth.Contains(searchTerm))).ToList();  
    

    Fixed the error, in other words removing the ToString(). I'm not sure why, butcan come up with ideas.