Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 获取实体框架中UnitOfWork和通用存储库中的特定列_C#_Entity Framework - Fatal编程技术网

C# 获取实体框架中UnitOfWork和通用存储库中的特定列

C# 获取实体框架中UnitOfWork和通用存储库中的特定列,c#,entity-framework,C#,Entity Framework,我有一个Windows窗体应用程序和通用实体框架最新版本的方法和多层设计模式 我希望加载特定列,而不是所有列 例如,我有10列a1…a10,但我想从a1。。。仅a8列。这是我获取所有列的代码-我该怎么做 存储库层: public Repository(GlobalERPEntities context) { Context = context; dbSet = Context.Set<T>(); } public virtual IEnumerable<T&g

我有一个Windows窗体应用程序和通用实体框架最新版本的方法和多层设计模式

我希望加载特定列,而不是所有列

例如,我有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层:从UnitOfWork层调用get all方法

protected UnitOfWork uow;

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

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

如何更改它以获得一组自定义列,以及如何在我的表单中调用它?

我为您提供了一个简单的解决方案,如下所示:首先编写IUnitOfWork,如下所示:

public interface IUnitOfWork
{
    IRepository<T> Repository<T>() where T : class;

    Task SaveChangesAsync();

    void ResetContextState();
}
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);
    }
}
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();
}
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;
    }
}
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();
      }
}
现在编写IRepository接口,如下所示:

public interface IUnitOfWork
{
    IRepository<T> Repository<T>() where T : class;

    Task SaveChangesAsync();

    void ResetContextState();
}
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);
    }
}
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();
}
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;
    }
}
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();
      }
}
然后在服务类或任何地方使用UnitOfWork,如下所示:

public interface IUnitOfWork
{
    IRepository<T> Repository<T>() where T : class;

    Task SaveChangesAsync();

    void ResetContextState();
}
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);
    }
}
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();
}
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;
    }
}
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();
      }
}
更好地使用依赖项注入,如下所示:

public interface IUnitOfWork
{
    IRepository<T> Repository<T>() where T : class;

    Task SaveChangesAsync();

    void ResetContextState();
}
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);
    }
}
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();
}
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;
    }
}
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();
      }
}

我给你一个简单的解决方案,如下所示:首先写下我的工作内容:

public interface IUnitOfWork
{
    IRepository<T> Repository<T>() where T : class;

    Task SaveChangesAsync();

    void ResetContextState();
}
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);
    }
}
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();
}
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;
    }
}
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();
      }
}
现在编写IRepository接口,如下所示:

public interface IUnitOfWork
{
    IRepository<T> Repository<T>() where T : class;

    Task SaveChangesAsync();

    void ResetContextState();
}
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);
    }
}
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();
}
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;
    }
}
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();
      }
}
然后在服务类或任何地方使用UnitOfWork,如下所示:

public interface IUnitOfWork
{
    IRepository<T> Repository<T>() where T : class;

    Task SaveChangesAsync();

    void ResetContextState();
}
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);
    }
}
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();
}
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;
    }
}
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();
      }
}
更好地使用依赖项注入,如下所示:

public interface IUnitOfWork
{
    IRepository<T> Repository<T>() where T : class;

    Task SaveChangesAsync();

    void ResetContextState();
}
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);
    }
}
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();
}
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;
    }
}
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();
      }
}

当我使用UnitOfWork模式时,我遵循的与Microsoft文档中指定的基本相同

您可以调整Get方法或添加一个新方法,如下所示。请注意,我们用于指定列的附加select参数:

public virtual IEnumerable<TDest> Get<TDest>(
    Expression<Func<TEntity, bool>> filter = null,
    Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
    string includeProperties = "",
    Expression<Func<TEntity, TDest>> select = null)
{
    IQueryable<TEntity> query = dbSet;

    if (filter != null)
    {
        query = query.Where(filter);
    }

    foreach (var includeProperty in includeProperties.Split
        (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
    {
        query = query.Include(includeProperty);
    }

    if (orderBy != null)
    {
        if (select == null)
            return (IEnumerable<TDest>)orderBy(query).ToList();

        return orderBy(query).Select(select).ToList();
    }
    else
    {
        if (select == null)
            (IEnumerable<TDest>)query.ToList();                

        return query.Select(select).ToList();
    }
}
示例使用


当我使用UnitOfWork模式时,我遵循的与Microsoft文档中指定的基本相同

您可以调整Get方法或添加一个新方法,如下所示。请注意,我们用于指定列的附加select参数:

public virtual IEnumerable<TDest> Get<TDest>(
    Expression<Func<TEntity, bool>> filter = null,
    Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
    string includeProperties = "",
    Expression<Func<TEntity, TDest>> select = null)
{
    IQueryable<TEntity> query = dbSet;

    if (filter != null)
    {
        query = query.Where(filter);
    }

    foreach (var includeProperty in includeProperties.Split
        (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
    {
        query = query.Include(includeProperty);
    }

    if (orderBy != null)
    {
        if (select == null)
            return (IEnumerable<TDest>)orderBy(query).ToList();

        return orderBy(query).Select(select).ToList();
    }
    else
    {
        if (select == null)
            (IEnumerable<TDest>)query.ToList();                

        return query.Select(select).ToList();
    }
}
示例使用


设计模式不重要,这是测试。我想选择自定义列。这是我的问题。只需将.Selectx=>new{a1,a2,…,a8}放在某个地方。我发现更好更简单的设计模式并不重要,这是一个测试。我想选择自定义列。这是我的问题。只需将.Selectx=>new{a1,a2,…,a8}放在某个地方。你决定在哪里。我发现更好、更简单,只是想一想,如果没有存储库模式和工作单元,这本可以在一行代码中完成,这是非常有效的!是啊!你说得对!就像_dbContext.Employees.Selectemp=>emp.Name.ToList;最佳设计模式。谢谢,但我有错误。你能帮我吗请过来pv@xxxsenatorxxx您还需要多少?@TanvirArjel我使用依赖注入EmployeeService,但在形式上,当我使用EmployeeService时,必须使用EmployeeServiceunitOfWork。在设计模式中,不必在形式上使用unitwork!试想一下,如果没有存储库模式和工作单元,这本可以在一行代码中完成,这是非常有效的!是啊!你说得对!就像_dbContext.Employees.Selectemp=>emp.Name.ToList;最佳设计模式。谢谢,但我有错误。你能帮我吗请过来pv@xxxsenatorxxx您还需要多少?@TanvirArjel我使用依赖注入EmployeeService,但在形式上,当我使用EmployeeService时,必须使用EmployeeServiceunitOfWork。在设计模式中,不必在形式上使用unitwork!