我为存储库操作创建了通用存储库模式。我想使用 Select 作为存储库的实例。我下面的代码解释了这种情况;
这是我的IGenericRepository;
public interface IGenericRepository<T> where T : class
{
Task<T> GetByIdAsync(Guid id);
/*.(like that methods...)*/
Task<T> Select(); //Which code should be here?
}
这是我的 GenericRepository 课程;
public class GenericRepository<T> : IGenericRepository<T> where T : class
{
private readonly Context _context;
private readonly DbSet<T> _dbContext;
public GenericRepository(Context context)
{
_context = context;
_dbContext = context.Set<T>();
}
public async Task<T> GetByIdAsync(Guid id)
{
return await _dbContext.FindAsync(id);
}
/*.(like that methods...)*/
public Task<T> Select(Expression<Func<T, bool>> predicate) //What should be parameter?
{
return _dbContext.Select() // which code should be here?
}
这是我的服务班;
public class ProfileService :IProfileService
{
private readonly IProfileRepository _profileRepository;
public ProfileService(IProfileRepository profileRepository)
{
_profileRepository = profileRepository;
}
public Task<ProfileUpdateResponseModel> UpdateProfile(ProfileUpdateRequestModel updateRequestModel)
{
var profile =_profileRepository.AsQueryable()
.Include(p => p.User)
.FirstOrDefault(p => p.User.Id == Guid.Parse(updateRequestModel.UserId))
.Select() // I can't use Select in there.. What I should?
}
}
我该如何处理?我必须使用没有存储库模式的选择方法?或者我对 Context 的实例是错误的吗?
通常,当您希望最大限度地减少管理域对象的数据库查询的冗余代码时,使用 GenericRepository 模式。因此,一般来说,它包含一些方法,例如
GetById
、Delete
、Update
、Create
以及存储库常见的其他方法。
有一个关于 GenericRepository + UoF 实现示例的链接。
据我了解,您的
Select()
方法应该返回给定谓词的一些数据,因此它可能如下所示:
public virtual IQueryable<TEntity> GetQuery(
Expression<Func<TEntity, bool>>? predicate = null,
params Expression<Func<TEntity, object>>[] navigationProperties)
{
IQueryable<TEntity> dbQuery = _dbSet.AsNoTracking();
if (predicate != null)
{
dbQuery = dbQuery.Where(predicate);
}
return navigationProperties.Aggregate(
dbQuery,
(current, navigationProperty) => current.Include(navigationProperty));
}
缺点之一是返回
IQueryable<TEntity>
:一些开发人员会说这不是一个好的做法,但这取决于你。我在here留下了该主题讨论的链接。
如果您需要一个返回
Task<IEnumerable<TEntity>>
的方法,只需将 GetQuery()
方法设为私有并按如下所示使用它:
public virtual async Task<IEnumerable<TEntity>> GetAllAsync(
Expression<Func<TEntity, bool>>? predicate = null,
CancellationToken token = default,
params Expression<Func<TEntity, object>>[] navigationProperties)
{
return await GetQuery(predicate, navigationProperties).ToListAsync(token);
}