没有支持的SQL转换

时间:2010-05-07 21:09:39

标签: linq-to-sql

我们有这段代码:

private IList<InfoRequest> GetBy(Func<InformationRequest, string> func, string searchby)
{
    var requests = _dc.InformationRequests
                      .Where(x => func.Invoke(x).Contains(searchby))
                      .OrderBy(y => y.RequestDate);

    return Mapper.Map<InformationRequest[], InfoRequest[]>(requests.ToArray());
}

它继续抛出不支持的转换为SQL错误。关于问题的任何想法或如何解决它?

2 个答案:

答案 0 :(得分:0)

我会接受这个link中的建议,将你的func转换为表达式,这将导致不同的重载.Where方法被调用。

 private IList<InfoRequest> GetBy(Expression<Func<InformationRequest, string>> exp, string searchby)
 {

      var requests = _dc.InformationRequests
                  .Where(x => exp(x).Contains(searchby))

答案 1 :(得分:0)

我最终得到了这个:

 private static Expression<Func<T, bool>> StartsWith<T>(Func<string, string> func)
{
    var searchBy = func.Method.GetParameters()[0].Name;
    var search = Expression.Constant(func(null), typeof(string));

    var searchByParam = Expression.Parameter(typeof(T), searchBy);
    var searchByExp = Expression.Property(searchByParam, searchBy);

    var methodInfo = typeof(string).GetMethod("StartsWith", new[] { typeof(string) });//, typeof(StringComparison)});
    var containsExpression = Expression.Call(searchByExp, methodInfo, search);

    return Expression.Lambda<Func<T, bool>>(containsExpression, searchByParam);
}

如果您想了解更多详情,请在此处发表博文:http://derans.blogspot.com/2010/05/building-l2s-expression-with-net-35.html