[英]C# Linq generic search
I am trying to write a method for a base repository service. 我正在尝试为基础存储库服务编写一种方法。 The idea is I want a generic class that can be used for simple entity types hat can also be overridden for more complex entities. 我的想法是我想要一个可以用于简单实体类型的泛型类,也可以为更复杂的实体覆盖。 I am writing a search method with the idea being that for simple entities there will be a component which will have one or more properties with fields which match properties of the entity. 我正在编写一种搜索方法,其想法是,对于简单实体,将存在一个组件,该组件将具有一个或多个属性,且字段与该实体的属性相匹配。 if these are found then build a where linq statement to query it. 如果找到了这些,则构建一个where linq语句来查询它。 Here's what I have so far: 这是我到目前为止的内容:
public IQueryable<T> GetAll()
{
return entityRepository.GetAll();
}
public IQueryable<T> Search(IBaseComponent component)
{
IQueryable<T> all = GetAll();
Type type = typeof(T);
Type componentType = component.GetType();
foreach (var componentProperty in componentType.GetProperties())
{
foreach (var property in type.GetProperties())
{
if (property.Name.Equals(componentProperty.Name))
{
var value = componentProperty.GetValue(component);
ParameterExpression gpe = Expression.Parameter(property.DeclaringType, "a");
var selector = Expression.Equal(Expression.Property(gpe, property), Expression.Constant(value));
var keySelector = Expression.Lambda(selector, gpe);
var t = all.Where(keySelector);
break;
}
}
}
var test = all.ToArray();
return all;
}
Obviously this would only theoretically work for one property at the moment. 显然,这目前仅在理论上适用于一种财产。 The service itself has a type parameter (so its BaseService<T>
). 服务本身具有类型参数(因此其BaseService<T>
)。
The problem I am having is that this will not compile. 我遇到的问题是它将无法编译。 The line all.Where(keySelector)
gives the error: 行all.Where(keySelector)
给出错误:
'System.Linq.IQueryable<T>' does not contain a definition for 'Where' and the best extension method overload 'System.Linq.Enumerable.Where<TSource>(System.Collections.Generic.IEnumerable<TSource>, System.Func<TSource,int,bool>)' has some invalid arguments
I'm not sure what's wrong here, they types are all correct as far as I can see. 我不确定这里出什么问题,据我所知,它们的类型都是正确的。 What am I missing? 我想念什么? Or am I trying to do something impossible? 还是我想做些不可能的事情?
Expression.Lambda
return type is LambdaExpression
even if the concrete type is Expression<Func<T, bool>>
( LambdaExpression
is the non generic base class for Expression<T>
) 即使具体类型为Expression<Func<T, bool>>
Expression.Lambda
返回类型也为LambdaExpression
( LambdaExpression
是Expression<T>
的非通用基类)
@Euphoric remark is spot on and the var
keyword is the problem here as the reason for this error would have been obvious without it. @Euphoric的评论很明显,而var
关键字是这里的问题,因为没有它,此错误的原因就很明显了。
The correct code is something like : 正确的代码是这样的:
var keySelector = (Expression<Func<T, bool>>)Expression.Lambda(selector, gpe);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.