Predicatebuilder与日期时间字符串比较

时间:2013-08-13 23:27:03

标签: linq entity-framework linqkit

我刚开始使用linq套件,我认为它很棒,但我有2个问题

我有这个项目的集合,可以通过几个条件进行过滤 a,b,c,d,e(非重要)和someDate(日期时间)

所以我有这样的谓词

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();

但是当我尝试使用

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

因为我没有使用特定日期进行比较而是使用不完整的字符串 例如8/1或08/01,也许只有8年或者也许只是年份,所以我不能在日期之间进行操作。

并抛出此错误。

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

我得到了这个link,因为linq to entities无法将日期时间解析为字符串,因为如果不同的文化设置。

即使我使用ToString(“d”),我也不愿意再次开始做这一切。

所以问题是

  

是否有人知道如何使谓词构建器与date.tostring()一起使用.contains()????

1 个答案:

答案 0 :(得分:2)

ToShortDateString是一个C#构造,数据库不理解它。只需在谓词构建器中直接比较日期。

//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?
相关问题