database - 如何将谓词与通用存储库一起使用
问题描述
我正在关注本教程 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();
}
我收到以下错误
- 无法将类型“字符串”隐式转换为“布尔”
- 无法将 lambda 表达式转换为委托类型“System.Func”,因为块中的某些返回类型不能隐式转换为委托返回类型
- 无法将类型“System.Collections.Generic.List”隐式转换为“DataModels.GEN_TransactionTypeSetup”
解决方案
您将能够在TEntity
实现中使用类型函数中的谓词。
假设你的TEntity
is 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()
。
推荐阅读
- node.js - 如何使用带有 mongoose@6.0.5 和 Nodejs 的 SSL 证书连接到 Mongodb?
- javascript - 按字母数字顺序排列数组并带有条件
- laravel - Laravel用camelCase创建方法
- ssh - 在两个远程主机之间传输文件,在本地拥有授权密钥?
- node.js - 如何从我的数据库查询中获取结果?
- flutter - 在flutter中覆盖提升按钮.icon内的标签和图标颜色?
- python - 在 S3 中获取最新上传文件的最简单方法是什么(当其他现有文件被覆盖时)-Python
- html - 锚标记不更改 URL
- javascript - NPM 包是否有“手册页”或 `--help`
- vba - 如何使用 VBA 自动将文件上传到 SAP