首页 > 解决方案 > 如何将谓词与通用存储库一起使用

问题描述

我正在关注本教程 https://www.codeproject.com/Articles/990492/RESTful-Day-sharp-Enterprise-Level-Application?msg=5635950#xx5635950xx 他很好地解释了简单的事情,但作为初学者我很难了解Generic Repository高级功能的实现

    public virtual IEnumerable<TEntity> GetMany(Func<TEntity, bool> 
    where)
    {
        return DbSet.Where(where).ToList();
    }

    /// <summary>
    /// generic method to get many record on the basis of a condition but 
    query able.
    /// </summary>
    /// <param name="where"></param>
    /// <returns></returns>
    public virtual IQueryable<TEntity> GetManyQueryable(Func<TEntity, 
    bool> where)
    {
        return DbSet.Where(where).AsQueryable();
    }

    /// <summary>
    /// generic get method , fetches data for the entities on the basis of 
        condition.
    /// </summary>
    /// <param name="where"></param>
    /// <returns></returns>
    public TEntity Get(Func<TEntity, Boolean> where)
    {
        return DbSet.Where(where).FirstOrDefault<TEntity>();
    }

我在我的服务文件中这样实现

      public GEN_TransactionTypeSetup GetTransactionIdByTableName(string 
       tableName)
        {
        IEnumerable<GEN_TransactionTypeSetup> list = 
        _unitOfWorks.TransactionType_Repository.GetMany(p => 
         p.Master_TableName = tableName);
        return list.ToList();
       }

我收到以下错误

标签: databaseentity-frameworkasp.net-web-api

解决方案


您将能够在TEntity实现中使用类型函数中的谓词。

假设你的TEntityis Person( GenericRepository<Person>) 并且你Person有一个属性Age,它是一个int.

然后你就可以说:

IEnumerable<Person> result = repository.GetMany(p => p.Age > 18);

如您所见,此(通用)方法返回一个IEnumerable<TEntity>,这意味着您可以将其他 Linq 方法应用(和链接)到您的结果中。

另请注意,ToList()

return DbSet.Where(where).ToList();

是多余的,并且在大型结果集中,可能会产生大量开销,因为该方法返回 an IEnumerable<TEntity>,因此 Linq 已经返回.Where()


推荐阅读