-1

I have a string 31-10-2014 wich i want to compare with a value in the database.

public ActionResult SearchResult(string searchDate)
{
    var bookings = from m in db.Bookings
                   select m;
    if (!String.IsNullOrEmpty(searchDate))
    {
        bookings = bookings.Where(s => s.Date1.CompareTo( DateTime.ParseExact(searchDate, "dd-mm-yyyy", CultureInfo.InvariantCulture)) >= 0);
    }
    return View(bookings);
}

the comparing keeps failing, How should i compare an input date to a database value (i left the try catch for validating the input to be an dattime so the example is more clear)

I get the message (even without searchData):

Linq doesn't recognise ParseExact method.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Sven van den Boogaart
  • 11,833
  • 21
  • 86
  • 169

4 Answers4

6

It's trying to compile DateTime.ParseExact into SQL, and failing. All you need is to define a variable and put the value into that variable, then use the variable in your query:

if (!String.IsNullOrEmpty(searchDate))
{
    DateTime dt = DateTime.ParseExact(searchDate, "dd-mm-yyyy", CultureInfo.InvariantCulture);
    bookings = bookings.Where(s => s.Date1 >= dt);
}
Joe Enos
  • 39,478
  • 11
  • 80
  • 136
2

It depends on what the variable db is. If it's a LINQ to SQL DataContext or EF DBContext, you can't use the methods you are using on date; there is no support. See this. There are SQL functions to work around that issue.

If you want raw SQL support for Dates, use the EntityFunctions class, which lets you do date comparisions. CompareTo is also not supported, so you'd have to use traditional greater than.

Community
  • 1
  • 1
Brian Mains
  • 50,520
  • 35
  • 148
  • 257
0

You have a - instead of an = in your code in Line #7.

Here's the right code.

public ActionResult SearchResult(string searchDate)
{
    var bookings = from m in db.Bookings
                   select m;
    if (!String.IsNullOrEmpty(searchDate))
    {
        bookings = bookings.Where(s => s.Date1.CompareTo( DateTime.ParseExact(searchDate, "dd-mm-yyyy", CultureInfo.InvariantCulture) >= 0);
    }
    return View(bookings);
}
Shiva
  • 20,575
  • 14
  • 82
  • 112
0

To make it in a simpler way, try this:

bookings = bookings.ToList().Where(s => s.Date1.CompareTo( DateTime.ParseExact(searchDate, "dd-mm-yyyy", CultureInfo.InvariantCulture)) >= 0);

Put it first in a list so that it will not take the DateTime.ParseExact as SQL statement since there's no DateTime.ParseExact in SQL.

Hope this helps

Louis Michael
  • 398
  • 1
  • 12