91 lines
2.6 KiB
C#
91 lines
2.6 KiB
C#
|
|
using Microsoft.EntityFrameworkCore;
|
|||
|
|
using HardwarePerformance.Application.Interfaces;
|
|||
|
|
using HardwarePerformance.Infrastructure.Data;
|
|||
|
|
|
|||
|
|
namespace HardwarePerformance.Infrastructure.Repositories
|
|||
|
|
{
|
|||
|
|
/// <summary>
|
|||
|
|
/// 通用Repository基类,实现基本的CRUD操作
|
|||
|
|
/// </summary>
|
|||
|
|
/// <typeparam name="T">实体类型</typeparam>
|
|||
|
|
public class Repository<T> : IRepository<T> where T : class
|
|||
|
|
{
|
|||
|
|
protected readonly AppDbContext _context;
|
|||
|
|
protected readonly DbSet<T> _dbSet;
|
|||
|
|
|
|||
|
|
public Repository(AppDbContext context)
|
|||
|
|
{
|
|||
|
|
_context = context;
|
|||
|
|
_dbSet = context.Set<T>();
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
public virtual async Task<T?> GetByIdAsync(int id)
|
|||
|
|
{
|
|||
|
|
return await _dbSet.FindAsync(id);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
public virtual async Task<IEnumerable<T>> GetAllAsync()
|
|||
|
|
{
|
|||
|
|
return await _dbSet.ToListAsync();
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
public virtual async Task<IEnumerable<T>> FindAsync(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
|
|||
|
|
{
|
|||
|
|
return await _dbSet.Where(predicate).ToListAsync();
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
public virtual async Task<bool> ExistsAsync(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
|
|||
|
|
{
|
|||
|
|
return await _dbSet.AnyAsync(predicate);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
public virtual async Task<T> AddAsync(T entity)
|
|||
|
|
{
|
|||
|
|
await _dbSet.AddAsync(entity);
|
|||
|
|
await _context.SaveChangesAsync();
|
|||
|
|
return entity;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
public virtual async Task<IEnumerable<T>> AddRangeAsync(IEnumerable<T> entities)
|
|||
|
|
{
|
|||
|
|
await _dbSet.AddRangeAsync(entities);
|
|||
|
|
await _context.SaveChangesAsync();
|
|||
|
|
return entities;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
public virtual async Task<T> UpdateAsync(T entity)
|
|||
|
|
{
|
|||
|
|
_dbSet.Update(entity);
|
|||
|
|
await _context.SaveChangesAsync();
|
|||
|
|
return entity;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
public virtual async Task<bool> DeleteAsync(T entity)
|
|||
|
|
{
|
|||
|
|
_dbSet.Remove(entity);
|
|||
|
|
await _context.SaveChangesAsync();
|
|||
|
|
return true;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
public virtual async Task<bool> DeleteByIdAsync(int id)
|
|||
|
|
{
|
|||
|
|
var entity = await GetByIdAsync(id);
|
|||
|
|
if (entity == null)
|
|||
|
|
{
|
|||
|
|
return false;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
return await DeleteAsync(entity);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
public virtual async Task<int> CountAsync()
|
|||
|
|
{
|
|||
|
|
return await _dbSet.CountAsync();
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
public virtual async Task<int> CountAsync(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
|
|||
|
|
{
|
|||
|
|
return await _dbSet.CountAsync(predicate);
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|