使用“单个"字样时,在动态Linq中 [英] Use of "Single" in Dynamic Linq

查看:60
本文介绍了使用“单个"字样时,在动态Linq中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将我在Linq中工作过的Linq查询转换为能够在动态linq中工作(使用System.Linq.Dynamic),因为我希望用户能够形成自己的查询和该查询字符串会在运行时添加到其他查询字符串中.

I am trying to convert a Linq query that I have working in Linq to be able to work in dynamic linq (using System.Linq.Dynamic) because I want a user to be able to form their own queries and this query string would be added onto other query strings at runtime.

我有一个查询:

db.incidents.Where(a => a.incidentLocations.Single().location.street.Contains(location);

,并且我尝试将其转换为以下动态linq字符串:

and I have tried to convert it to the following dynamic linq string:

query = 
string.Concat("incidentLocations.Single().location.street.Contains(\"", location, "\")");

db.incidents.Where(query);

位置是包含搜索文本的字符串.

Where location is a string that includes search text.

我设法将所有其他查询都转换为动态linq,但是我正在为异常错误而苦苦挣扎:

I have managed to convert all my other queries to dynamic linq but this one i am struggling with the exception error:

不存在适用的聚合方法单一""

"No applicable aggregate method 'Single' exists"

我知道动态linq并不支持所有扩展方法,有人可以告诉我如何解决这个问题.

I understand that dynamic linq does not support all extension methods, could someone possibly tell me how I could get round this problem.

推荐答案

获取Linq.Dynamic的源代码,复制粘贴Where方法,更改方法内部的签名和带有函数名称的字符串,您可以去.我这样做是为了添加Single First等,我无法在这里复制它,因为我不在开发机器上,但是如果需要的话我会在以后做;)

Get the source of Linq.Dynamic, copy paste the Where method, change the signature and the string with the function name inside the method and you're good to go. I did it to add Single First etc, I can't copy it here because I'm not on my dev machine but I'll do it later if necessary ;)

如果您决定使用单方法,则为以下方法:

here's the Single method if you decide to use it:

public static object Single(this IQueryable source)
    {
        if (source == null) throw new ArgumentNullException("source");
        return source.Provider.Execute(
            Expression.Call(
                typeof(Queryable), "Single",
                new Type[] { source.ElementType },
                source.Expression));
    }

这篇关于使用“单个"字样时,在动态Linq中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆