我where
在linq查询的子句中使用函数时遇到问题,如以下代码所示。
返回IEnumerable
对象的函数:
private IEnumerable filterparameter(string filter) { EmailAflAwmMessageDM obj = new EmailAflAwmMessageDM(); if (filter == "attachments") { return obj.attachments; } else if (filter == "flagged") { return obj.flagged; } else { return obj.seen; } }
返回的函数IQuerable
,将在Web api函数中使用:
private IQueryable SearchFilterCondition(string filter,string value) { var emailmessage = from a in db.EmailAflAwmMessage where (filterparameter(filter) == value) orderby a.msg_date descending select new { a.subject, a.msg_date, }; return emailmessage; }
更新:此错误
{"Message":"An error has occurred.", "ExceptionMessage":"The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.", "ExceptionType":"System.InvalidOperationException", "StackTrace":null, "InnerException": { "Message":"An error has occurred.", "ExceptionMessage":"LINQ to Entities does not recognize the method 'System.Collections.IEnumerable filterparameter(System.String)' method, and this method cannot be translated into a store expression.", "ExceptionType":"System.NotSupportedException", "StackTrace":"
请帮助我解决此问题或指导我。
正如提到的@Domysee所述,您不能在Linq查询中调用任何c#函数。仅EntitiFunctions 这就是为什么要为其构建表达式的原因。在linq查询中使用
public Expression> GetSelectXpr(string filter, string value) { if (filter == "attachments") return e => e.attachments == value; else if (filter == "flagged") return e => e.flagged == value; else return e => e.seen == value; }
用法。
var selectXpr = GetGetSelectXpr(filter,value); var emailmessage = db.EmailAflAwmMessage.Where(selectXpr).OrderByDescending(a=>a.msg_date).Select(a=> new { a.subject, a.msg_date })