Question

i just start using linq kit and i think it's awesome but i have a 2 problems

i have this collection of items that can be filtered by several conditions a,b,c,d,e(non important) and someDate (datetime)

so i have a predicate like this

var predicate = PredicateBuilder.True<Item>();

if (!string.IsNullOrEmpty(filter))
        {
            predicate = predicate.And(p => p.a.Contains(filter));
            predicate = predicate.Or(p => p.b.Value.Contains(filter));
            predicate = predicate.Or(p => p.c.Value.Contains(filter));
            predicate = predicate.Or(p => p.d.Name.Contains(filter));
            predicate = predicate.Or(p => p.e.Contains(filter));
        }
// Get items depending on previous predicate
        var items= (from item in _context.Items.AsExpandable()
                           select item).Where(predicate).Where(m => m.Active).ToList();

but when i try to use

predicate = predicate.Or(p => p.someDate.ToShortDateString().Contains(filter));

because im not using a specific date to compare but a incomplete string such as 8/1 or 08/01, maybe just 8 or maybe just the year, so i cannot make an operation between dates.

and throws this error.

LINQ to Entities does not recognize the method 'System.String ToShortDateString()' method, and this method cannot be translated into a store expression.

and i got from this link that its because linq to entities can't parse the date time to string because if the different culture settings.

even if i use ToString("d") i would hate to start to do all this all over again.

so the question is

Does anybody knows a way to make the predicate builder work with date.tostring().contains() ????

Était-ce utile?

La solution

ToShortDateString is a C# construct and the database doesn't understand it. Just compare the dates directly in your predicate builder.

//use some kind of operator. I chose ==.
//if you are passing a date as a string, you need to parse that date first, then do the comparison.
DateTime filterDate;
if(DateTime.TryParse(filter, out filterDate))
   predicate = predicate.Or(p => p.someDate == filterDate);
//Why would you do the date conversion to a string and see if that date contains another string?
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top