Я даю вам надежное решение следующим образом: сначала напишите IUnitOfWork
следующим образом:
public interface IUnitOfWork
{
IRepository<T> Repository<T>() where T : class;
Task SaveChangesAsync();
void ResetContextState();
}
Тогда UnitOfWork
класс следующим образом:
public class UnitOfWork : IUnitOfWork
{
private readonly YourDbContext _dbContext;
private Hashtable _repositories;
public UnitOfWork(YourDbContext dbContext)
{
_dbContext = dbContext;
}
public IRepository<T> Repository<T>() where T : class
{
if (_repositories == null)
_repositories = new Hashtable();
var type = typeof(T).Name;
if (!_repositories.ContainsKey(type))
{
var repositoryType = typeof(Repository<>);
var repositoryInstance =
Activator.CreateInstance(repositoryType
.MakeGenericType(typeof(T)), _dbContext);
_repositories.Add(type, repositoryInstance);
}
return (IRepository<T>)_repositories[type];
}
public async Task SaveChangesAsync()
{
await _dbContext.SaveChangesAsync();
}
public void ResetContextState()
{
_dbContext.ChangeTracker.Entries().Where(e => e.Entity != null).ToList()
.ForEach(e => e.State = EntityState.Detached);
}
}
Теперь напишите IRepository
интерфейс следующим образом:
public interface IRepository<TEntity> where TEntity : class
{
IQueryable<TEntity> GetEntities(Expression<Func<TEntity, bool>> condition = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = "");
Task<bool> IsEntityExists(Expression<Func<TEntity, bool>> filter = null);
void InsertEntity(TEntity entity);
void InsertEntities(List<TEntity> entities);
void UpdateEntity(TEntity entity, params string[] excludeProperties);
void DeleteEntity(TEntity entity);
void DeleteEntities(List<TEntity> entities);
Task<bool> IsTableEmptyAsync();
}
Тогда ваш Repository
класс выглядит следующим образом:
public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
{
private readonly YourDbContext _dbContext;
private readonly DbSet<TEntity> _dbSet;
public Repository(YourDbContext dbContext)
{
_dbContext = dbContext;
_dbSet = _dbContext.Set<TEntity>();
}
public IQueryable<TEntity> GetEntities(Expression<Func<TEntity, bool>> condition = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = "")
{
IQueryable<TEntity> query = _dbSet;
if (condition != null)
{
query = query.Where(condition);
}
foreach (var includeProperty in includeProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
if (orderBy != null)
{
query = orderBy(query);
}
return query;
}
public async Task<bool> IsEntityExists(Expression<Func<TEntity, bool>> condition)
{
bool status = false;
if (condition != null)
{
status = await _dbSet.AnyAsync(condition);
}
return status;
}
public void InsertEntity(TEntity entity)
{
_dbSet.Add(entity);
}
public void InsertEntities(List<TEntity> entities)
{
_dbSet.AddRange(entities);
}
public void UpdateEntity(TEntity entity, params string[] excludeProperties)
{
_dbContext.Entry(entity).State = EntityState.Modified;
foreach (string property in excludeProperties)
{
_dbContext.Entry(entity).Property(property).IsModified = false;
}
}
public void DeleteEntity(TEntity entity)
{
_dbSet.Remove(entity);
}
public void DeleteEntities(List<TEntity> entities)
{
_dbSet.RemoveRange(entities);
}
public async Task<bool> IsTableEmptyAsync()
{
bool hasAny = await _dbSet.AnyAsync();
return !hasAny;
}
}
Затем используйте UnitOfWork
в своем классе обслуживания или в любом месте следующим образом:
public class EmployeeService
{
private readonly UnitOfWork _unitOfWork;
public EmployeeService()
{
_unitOfWork = new UnitOfWork();
}
public List<Employee> GetAllEmployees()
{
return _unitOfWork.Repository<Employee>().GetEntities().ToList();
}
public List<string> GetAllEmployeeNames()
{
return _unitOfWork.Repository<Employee>().GetEntities().Select(emp => emp.Name).ToList();
}
}
Лучше использовать с внедрением зависимости следующим образом:
public class EmployeeService
{
private readonly IUnitOfWork _unitOfWork;
public EmployeeService(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
public List<Employee> GetAllEmployees()
{
return _unitOfWork.Repository<Employee>().GetEntities().ToList();
}
public List<string> GetAllEmployeeNames()
{
return _unitOfWork.Repository<Employee>().GetEntities().Select(emp => emp.Name).ToList();
}
}