generics - IfExist 在通用存储库中
问题描述
我使用通用存储库和 unitofwork(.net core) 并尝试构建 IfExist 函数,
1:接口
bool IsExistRecord<type>(type Id);
2- 实施
public bool IsExistRecord<type>(type Id)
{
var query = DbSet.Find(Id);
if (query != null)
{
return true;
}
return false;
}
3-使用它。
_unitOfWork.GetRepository<EntityName>().IsExistRecord(id);
但在这种情况下,我尝试只检查表的主键,
如何检查表中的任何列作为代码,名字?!任何帮助
解决方案
您只需要为您的存储库提供这样的扩展方法(或者您可以将其转换并直接添加到存储库)
/// <summary>
/// Gets a value indicating whether or not the record exists by query
/// </summary>
/// <param name="repository">Repository Instance</param>
/// <param name="predicate">Query Predicate</param>
/// <returns>True if the object exists</returns>
public static bool DoesExist<TEntity>(this IRepository<TEntity> repository, Expression<Func<TEntity, bool>> predicate) where TEntity : class
{
return repository.Get(p => p.Where(predicate)).FirstOrDefault() != null;
}
然后像这样调用它:
_unitOfWork.GetRepository<EntityName>().DoesExist(p => p.FirstName == "Robert");
推荐阅读
- scala - 组合柯里化函数
- sql-server - 在 SSMS 中,登录名右侧显示的数字是多少?
- android - 错误:(246, 5) 错误:资源 'attr/font' 与配置 '' 的重复值
- vba - 行源行为在不重新加载用户表单的情况下不更新/重置列表框 // 使用 list = 范围获取列标题
- oracle - 未启用 Oracle 约束
- r - 矩阵中特定行的行和
- wpf - 样式中的 WPF 命令绑定 ItemsControl
- arangodb - Arango 查询,带有边缘计数的集合
- ionic-framework - Ionic 3 图像映射问题
- python - Django 管理员。当对象具有布尔字段== True时,如何为列表视图中的每一行添加背景颜色?