[英]linq function for use with generic repository entity in where clause
I want to use a generic repository to standardise some of my data access. 我想使用通用存储库来标准化一些数据访问。 What I want is to be able to have a function defined in the interface representing the basic fields of my entity, so that I can use it to filter the results. 我想要的是能够在表示我的实体基本字段的接口中定义一个函数,以便可以使用它来过滤结果。 This should be compilable into Linq-To-Sql. 这应该可以编译成Linq-To-Sql。
eg 例如
interface IEntity {
Expression<func<bool>> FilterQuery(string filter)
}
partial class AnEntity : IEntity
{
public string AName {get; set;}
Expression<func<bool>> FilterQuery(string filter)
{
return AName.Contains(filter);
}
}
class List<T> : where T : class, IEntity
{
private IQueryable<T> items;
public IQueryable<T> show(string filter)
{
items = items.Where(AN => AN.FilterQuery(filter));
return items;
}
}
However, I typically get errors like: 但是,我通常会收到如下错误:
Cannot convert lambda expression to delegate type '
System.Func<T,int,bool>
' because some of the return types in the block are not implicitly convertible to the delegate return type 无法将lambda表达式转换为委托类型'System.Func<T,int,bool>
',因为块中的某些返回类型不能隐式转换为委托返回类型
What is the best way of achieving my goal, of having something generic defined on an entity which can be using in a linq to sql where clause? 实现目标的最佳方法是在实体上定义可在linq to sql where子句中使用的泛型?
The lambda for Where
needs to take the entity type; Where
的lambda需要采用实体类型; I would expect that you would need: 我希望您需要:
interface IEntity<T> where T : class {
Expression<Func<T, bool>> FilterQuery(string filter);
}
partial class AnEntity : IEntity<AnEntity>
{
public string AName {get; set;}
Expression<Func<AnEntity,bool>> IEntity<AnEntity>.FilterQuery(string filter)
{
return x => x.AName.Contains(filter);
}
}
However; 然而; the FilterQuery
method doesn't feel like an entity responsibility... (separation of concerns); FilterQuery
方法感觉不像是一个实体责任...(关注点分离); which is why it isn't helpful in the "list" case; 这就是为什么它在“列表”情况下没有帮助的原因; maybe you need to move that to the list? 也许您需要将其移至列表? But when it works, something like: 但是当它起作用时,类似:
T template = new T(); // this is a horrible way to get the filter!!!
// and illustrates that this method doesn't belong on
// this type; only done this way to fit the question's
// pretext - which I believe is... suboptimal.
var filterQuery = template.FilterQuery(filter);
items = items.Where(filterQuery);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.