2010-05-07 53 views
0

我們有這樣的代碼:不支持轉換爲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錯誤。關於問題的任何想法或如何解決?

+0

包含支持,但你的FUNC不是。提供一些關於你想用Func做什麼的更多信息。這是你的問題。 Linq to SQL無法將Expression推送到數據庫。 – Nix 2010-05-07 21:59:42

回答

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)) 
+0

是的,我也試過這個。它不給我選擇通過InformationRequest。我必須這樣做:.Where(x => exp.Compile()。Invoke(x).Contains(searchby)) 在這一點上,它給出了和以前相同的錯誤。 – derans 2010-05-07 23:25:59

+0

你可以請張貼你的func嗎? – Nix 2010-05-08 13:34:05

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