我在linq查询中的where
子句中使用函数时遇到问题,如下代码所示。
-
返回
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#函数。仅EntitiFunction这就是为什么表达式是为之构建的。要在linq查询中使用
public Expression<Func<EmailAflAwmMessage, bool>> 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
})
不幸的是,不可能在IQueryable
的Where
中使用方法,因为Linq-to-SQL不知道如何将方法转换为SQL。
您必须将方法内联到Where
中才能使其工作
类似的东西:
private IQueryable SearchFilterCondition(string filter,string value)
{
var filterParam = filterparameter(filter); //evaluate filterparameter outside of the query
var emailmessage = from a in db.EmailAflAwmMessage
where (filterParam == value)
orderby a.msg_date descending
select new
{
a.subject,
a.msg_date,
};
return emailmessage;
}