Получить конкретные столбцы в UnitOfWork и общий репозиторий в Entity Framework - PullRequest
0 голосов
/ 12 января 2019

У меня есть приложение Windows Forms и универсальный метод Entity Framework (последняя версия) и шаблон многоуровневого проектирования.

Я хочу загрузить определенные столбцы, а не все столбцы.

Например, у меня есть 10 столбцов (a1 ... a10), но я хочу получать данные только из (a1 ... a8) столбцов. Это мой код для получения всех столбцов - как мне это сделать?

Слой репозитория:

public Repository(GlobalERPEntities context)
{
    Context = context;
    dbSet = Context.Set<T>();
}

public virtual IEnumerable<T> GetAll()
{
    return dbSet.ToList();
}

Уровень UnitOfWork: вызов метода get all из уровня хранилища

public UnitOfWork()
{
    Context = new GlobalERPEntities();
}

public Repository<T> Repository<T>() where T : class
{
    if (repositories == null)
    {
        repositories = new Dictionary<Type, object>();
    }

    if (repositories.Keys.Contains(typeof(T)) == true)
    {
        return repositories[typeof(T)] as Repository<T>;
    }

    Repository<T> repo = new Repository<T>(Context);
    repositories.Add(typeof(T), repo);

    return repo;
}

Слой BLL: вызов метода get all из слоя UnitOfWork

protected UnitOfWork uow;

public Service()
{
    uow = new UnitOfWork();
}

public virtual IEnumerable<T> GetAll()
{
    return uow.Repository<T>().GetAll().ToList();
}

Как изменить его, чтобы получить пользовательский набор столбцов, и как вызвать его в моей форме?

1 Ответ

0 голосов
/ 12 января 2019

Я даю вам надежное решение следующим образом: сначала напишите 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();
      }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...