我正在阅读一篇非常酷的文章,内容涉及使用以下链接https://blog.zhaytam.com/2019/03/14/generic-repository-pattern-csharp/创建通用Async存储库该接口将所有操作定义为任务,但是实现选择在某些方法上不使用async / await模式。我想进一步了解这一点,因此决定在此处发布。乍一看,客户端似乎可能不知道他们需要等待未标记为异步的方法,但我可能无法正确理解。任何人都可以评论为什么作者选择不对某些返回任务的方法而不是对其他方法使用异步吗?
public interface IAsyncRepository<T> where T : BaseEntity
{
Task<T> GetById(int id);
Task<T> FirstOrDefault(Expression<Func<T,bool>> predicate);
Task Add(T entity);
Task Update(T entity);
Task Remove(T entity);
Task<IEnumerable<T>> Getall();
Task<IEnumerable<T>> GetWhere(Expression<Func<T,bool>> predicate);
Task<int> CountAll();
Task<int> CountWhere(Expression<Func<T,bool>> predicate);
}
public class EfRepository<T> : IAsyncRepository<T> where T : BaseEntity
{
#region Fields
protected DataDbContext Context;
#endregion
public EfRepository(DataDbContext context)
{
Context = context;
}
#region Public Methods
public Task<T> GetById(int id) => Context.Set<T>().FindAsync(id);
public Task<T> FirstOrDefault(Expression<Func<T,bool>> predicate)
=> Context.Set<T>().FirstOrDefaultAsync(predicate);
public async Task Add(T entity)
{
// await Context.AddAsync(entity);
await Context.Set<T>().AddAsync(entity);
await Context.SaveChangesAsync();
}
public Task Update(T entity)
{
// In case AsnoTracking is used
Context.Entry(entity).State = EntityState.Modified;
return Context.SaveChangesAsync();
}
public Task Remove(T entity)
{
Context.Set<T>().Remove(entity);
return Context.SaveChangesAsync();
}
public async Task<IEnumerable<T>> Getall()
{
return await Context.Set<T>().ToListAsync();
}
public async Task<IEnumerable<T>> GetWhere(Expression<Func<T,bool>> predicate)
{
return await Context.Set<T>().Where(predicate).ToListAsync();
}
public Task<int> CountAll() => Context.Set<T>().CountAsync();
public Task<int> CountWhere(Expression<Func<T,bool>> predicate)
=> Context.Set<T>().CountAsync(predicate);
#endregion
}