如何扩展 DynamicQuery.cs 来实现 .Single 方法?
我需要为我正在从事的项目编写一些动态查询。我发现我的程序在 Count 和 First 方法上花费了大量时间,因此我开始更改为 .Single,却发现没有这样的方法。
下面的代码是我第一次尝试创建代码(大部分是从Where 方法复制的),但它不起作用。帮助?
public static object Single(this IQueryable source, string predicate, params object[] values)
{
if (source == null) throw new ArgumentNullException("source");
if (predicate == null) throw new ArgumentNullException("predicate");
LambdaExpression lambda = DynamicExpression.ParseLambda(source.ElementType, typeof(bool), predicate, values);
return source.Provider.CreateQuery(
Expression.Call(
typeof(Queryable), "Single",
new Type[] { source.ElementType },
source.Expression, Expression.Quote(lambda)));
}
I need to write some dynamic queries for a project I'm working on. I'm finding out that a significant amount of time is being spent by my program on the Count and First methods, so I started to change to .Single, only to find out that there is no such method.
The code below was my first attempt at creating one (mostly copied from the Where method), but it's not working. Help?
public static object Single(this IQueryable source, string predicate, params object[] values)
{
if (source == null) throw new ArgumentNullException("source");
if (predicate == null) throw new ArgumentNullException("predicate");
LambdaExpression lambda = DynamicExpression.ParseLambda(source.ElementType, typeof(bool), predicate, values);
return source.Provider.CreateQuery(
Expression.Call(
typeof(Queryable), "Single",
new Type[] { source.ElementType },
source.Expression, Expression.Quote(lambda)));
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
恕我直言,在执行查询时,您应该只使用
Single
或SingleOrDefault
。因此,我认为动态 linq 没有必要使用“单一”运算符。特别是,查询枚举返回的
IEnumerable
或IQueryable
只能包含一项。IMHO, you should just simply can use
Single
orSingleOrDefault
when you are executing the query.So, I do not see the necessity for a "Single" operator for dynnamic linq. Especially, as the
IEnumerable
orIQueryable
returned by the query enumeration should only contain one item.我不明白您填写的 Single(SingleOrDefault) 和 First(FirstOrDefault) 之间有什么区别?
此外,EF 不实现第一个,您必须使用 First(FirstOrDefault) 代替。
另外,为什么你填写你将通过创建你自己的 single 实现来获得性能改进,这是你的评论几乎是 where 的副本,这与第一个几乎相同
那么为什么不使用它,并尝试查看正在生成的查询并分析它们呢?
I don't understand what the difference you fill to be between Single(SingleOrDefault) and First(FirstOrDefault) ?
Moreover EF do not implement the first one and you have to use First(FirstOrDefault) instead.
Also why do you fill you will gain perfomance improvement by creating your own implementation of single , which is by your comment almost a copy of where , which is almost the same as first
so why do not use it , and try to look at query's being generated and analyse them ?
我认为 Queryable.Single 就是您正在寻找的。
I think
Queryable.Single
is what you're looking for.