搜索一个名为 GenericRepository 的概念。它将有助于摆脱每个实体问题的存储库。下面的示例:
public interface IGenericRepository<T> where T : class
{
IEnumerable<T> GetAll();
T SingleOrDefault(Expression<Func<T, bool>> predicate);
IEnumerable<T> Get(Expression<Func<T, bool>> predicate);
void Insert(T entity);
void Update(T entity);
void Delete(object id);
void Delete(T entity);
}
public class GenericRepository<T> : IGenericRepository<T> where T : class
{
readonly MyDbContext _context;
readonly DbSet<T> _dbSet;
public GenericRepository(PfsDbContext context)
{
_context = context;
_dbSet = context.Set<T>();
}
public virtual IEnumerable<T> GetAll()
{
return _dbSet.AsEnumerable();
}
public T SingleOrDefault(Expression<Func<T, bool>> predicate)
{
return _dbSet.Where(predicate).SingleOrDefault();
}
public IEnumerable<T> Get(Expression<Func<T, bool>> predicate)
{
return _dbSet.Where(predicate);
}
public void Insert(T entity)
{
_dbSet.Add(entity);
}
public void Update(T entityToUpdate)
{
_dbSet.Attach(entityToUpdate);
_context.Entry(entityToUpdate).State = EntityState.Modified;
}
public void Delete(T entity)
{
if (_context.Entry(entity).State == EntityState.Detached)
{
_dbSet.Attach(entity);
}
_dbSet.Remove(entity);
}
public void Delete(object id)
{
var entityToDelete = _dbSet.Find(id);
Delete(entityToDelete);
}
}
然后,您可以将其用作
var userRepository = new GenericRepository<User>(_context);
var journeyRepository = new GenericRepository<Journey>(_context);