当前位置:  开发笔记 > 编程语言 > 正文

如何在LINQ查询的where子句中将方法/函数作为IEnumerable对象调用

如何解决《如何在LINQ查询的where子句中将方法/函数作为IEnumerable对象调用》经验,为你挑选了1个好方法。

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":"

请帮助我解决此问题或指导我。



1> Anestis Kivr..:

正如提到的@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
   })

推荐阅读
我我檬檬我我186
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有