c# – 如何在LINQ查询的where子句中调用方法/函数作为IEnumerabl
发布时间:2020-12-15 23:29:21 所属栏目:百科 来源:网络整理
导读:我有问题在 linq查询中的where子句中使用函数,如下面的代码所示. 返回IEnumerable对象的函数: private IEnumerable filterparameter(string filter) { EmailAflAwmMessageDM obj = new EmailAflAwmMessageDM(); if (filter == "attachments") { return obj.
我有问题在
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#函数.只有
EntitiFunctions
这就是为什么表达式已经构建的原因.要在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 }) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |