测试
This commit is contained in:
60
MinimalAPI/Repositories/Repository.cs
Normal file
60
MinimalAPI/Repositories/Repository.cs
Normal file
@@ -0,0 +1,60 @@
|
||||
using System.Linq.Expressions;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using HardwarePerformance.Data;
|
||||
using HardwarePerformance.Models;
|
||||
|
||||
namespace HardwarePerformance.Repositories
|
||||
{
|
||||
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 async Task<T?> GetByIdAsync(int id)
|
||||
{
|
||||
return await _dbSet.FindAsync(id);
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<T>> GetAllAsync()
|
||||
{
|
||||
return await _dbSet.ToListAsync();
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<T>> FindAsync(Expression<Func<T, bool>> predicate)
|
||||
{
|
||||
return await _dbSet.Where(predicate).ToListAsync();
|
||||
}
|
||||
|
||||
public async Task<T> AddAsync(T entity)
|
||||
{
|
||||
await _dbSet.AddAsync(entity);
|
||||
await _context.SaveChangesAsync();
|
||||
return entity;
|
||||
}
|
||||
|
||||
public async Task UpdateAsync(T entity)
|
||||
{
|
||||
_dbSet.Update(entity);
|
||||
await _context.SaveChangesAsync();
|
||||
}
|
||||
|
||||
public async Task DeleteAsync(T entity)
|
||||
{
|
||||
_dbSet.Remove(entity);
|
||||
await _context.SaveChangesAsync();
|
||||
}
|
||||
|
||||
public async Task<int> CountAsync(Expression<Func<T, bool>>? predicate = null)
|
||||
{
|
||||
if (predicate == null)
|
||||
return await _dbSet.CountAsync();
|
||||
return await _dbSet.CountAsync(predicate);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user