linq函数用于where子句中的通用存储库实体

时间:2009-09-29 15:18:26

标签: c# linq linq-to-sql

我想使用通用存储库来标准化我的一些数据访问。 我想要的是能够在界面中定义一个代表我的实体的基本字段的函数,以便我可以使用它来过滤结果。这应该可以编译成Linq-To-Sql。

e.g。

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;
  }
}

但是,我通常会遇到如下错误:

  

无法将lambda表达式转换为   代表类型   'System.Func<T,int,bool>'因为   块中的一些返回类型   不能隐含地转换为   委托返回类型

实现我的目标的最佳方法是什么,在可以在linq到sql where子句中使用的实体上定义泛型?

1 个答案:

答案 0 :(得分:1)

Where的lambda需要采用实体类型;我希望你需要:

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);
  }
}

然而; FilterQuery方法不像实体责任......(关注点分离);这就是为什么它在“列表”案例中没有帮助;也许你需要把它移到列表中?但是当它起作用时,就像:

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);
相关问题