如何通过ASP.NET Core 2中分离的类库正确实现存储库模式和工作单元?

时间:2018-10-12 11:32:46

标签: c# asp.net-core entity-framework-core

我正在使用ASP.NET Core API 2创建项目,我想在单独的类库中正确实现存储库模式和工作单元。某种程度上,我对实现感到困惑,我只熟悉使用ASP.NET MVC 5的实现。请问,我想知道一些建议,如果可能的话,在ASP.NET Core 2中可以做到这一点?

Project.API

appsettings.json

{
  "ConnectionStrings": {
    "DbConnectionString": "Server=HOST; Database=DB_NAME; User Id=sa; Password=Password;"
  },
  "Logging": {
    "IncludeScopes": false,
    "Debug": {
      "LogLevel": {
        "Default": "Warning"
      }
    },
    "Console": {
      "LogLevel": {
        "Default": "Warning"
      }
    }
  }
}

Startup.cs

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<DatninContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DbConnectionString")));

            services
                .AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        public void Configure(IApplicationBuilder applicationBuilder, IHostingEnvironment hostingEnvironment)
        {
            if (hostingEnvironment.IsDevelopment()) applicationBuilder.UseDeveloperExceptionPage();

            applicationBuilder.UseCors(AllRequests);
            applicationBuilder.UseStaticFiles();
            applicationBuilder.UseMvc();
        }
    }

Project.Persistence

EntityConfigurations文件夹

public class EmployeeConfiguration : IEntityTypeConfiguration<Employee>
    {
        public void Configure(EntityTypeBuilder<Employee> builder)
        {
            throw new NotImplementedException();
        }
    }

存储库实施

public class EmployeeRepository : BaseRepository<Employee>, IEmployeeRepository
    {
        public AnimeRepository(ProjectDbContext context) : base(context)
        {
        }

        public ProjectDbContext ProjectDbContext => Context as ProjectDbContext;

        public async Task<IEnumerable<Employee>> GetEmployeesAsync()
        {
            var employees = await ProjectDbContext.Employees.ToListAsync();

            return employees;
        }

        public async Task<Employee> GetEmployeeWithIdAsync(Guid id)
        {
            var employee = await DatninContext.Employees.SingleOrDefaultAsync(a => a.Id == id);

            return employee;
        }
    }

基本存储库实现

public class BaseRepository<TEntity> : IBaseRepository<TEntity> where TEntity : class
    {
        protected readonly DbContext Context;

        public BaseRepository(DbContext context)
        {
            Context = context;
        }

        public async Task<TEntity> GetAsync(int id)
        {
            return await Context.Set<TEntity>().FindAsync(id);
        }

        public async Task<IEnumerable<TEntity>> GetAllAsync()
        {
            return await Context.Set<TEntity>().ToListAsync();
        }

        public async Task<TEntity> SingleOrDefaultAsync(Expression<Func<TEntity, bool>> predicate)
        {
            return await Context.Set<TEntity>().SingleOrDefaultAsync(predicate);
        }

        public async Task<IEnumerable<TEntity>> FindAsync(Expression<Func<TEntity, bool>> predicate)
        {
            return await Context.Set<TEntity>().Where(predicate).ToListAsync();
        }

        public async Task AddAsync(TEntity entity)
        {
            await Context.Set<TEntity>().AddAsync(entity);
        }

        public async Task AddRangeAsync(IEnumerable<TEntity> entities)
        {
            await Context.Set<TEntity>().AddRangeAsync(entities);
        }

        public void Remove(TEntity entity)
        {
            Context.Set<TEntity>().Remove(entity);
        }

        public void RemoveRange(IEnumerable<TEntity> entities)
        {
            Context.Set<TEntity>().RemoveRange(entities);
        }
    }

ProjectDbContext.cs

public class ProjectDbContext : DbContext
    {
        public ProjectDbContext(DbContextOptions<ProjectDbContext> options) : base(options)
        {
        }

        public virtual DbSet<Employee> Employees { get; set; }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);

        builder.ApplyConfiguration(new EmployeeConfiguration());

        }
    }

工作单元实施

public class UnitOfWork : IUnitOfWork
    {
        private readonly ProjectDbContext _context;

        public UnitOfWork(ProjectDbContext context)
        {
            _context = context;
            Employees = new EmployeeRepository(_context);
        }

        public IEmployeeRepository Employees { get; }

        public int Complete()
        {
            return _context.SaveChanges();
        }

        public void Dispose()
        {
            _context.Dispose();
        }
    }

Propject.Core

实体

Employee.cs

public class Employee 
    {
public int Id { get; set; }
        public string Name { get; set; }
        public string Position { get; set; }
        public string Department { get; set; }
public string Salary { get; set; }
    }

IBaseRepository.cs

public interface IBaseRepository<TEntity> where TEntity : class
    {
        Task<TEntity> GetAsync(int id);
        Task<IEnumerable<TEntity>> GetAllAsync();
        Task<TEntity> SingleOrDefaultAsync(Expression<Func<TEntity, bool>> predicate);
        Task<IEnumerable<TEntity>> FindAsync(Expression<Func<TEntity, bool>> predicate);
        Task AddAsync(TEntity entity);
        Task AddRangeAsync(IEnumerable<TEntity> entities);
        void Remove(TEntity entity);
        void RemoveRange(IEnumerable<TEntity> entities);
    }

IEmployeeRepository.cs

public interface IEmployeeRepository : IBaseRepository<Employee>
    {
        Task<IEnumerable<Employee>> GetEmployeesAsync();
        Task<Anime> GetEmployeeWithIdAsync(Guid id);
    }

IUnitOfWork.cs

 public interface IUnitOfWork : IDisposable
    {
        IEmployeeRepository Employees { get; }
        int Complete();
    }`

0 个答案:

没有答案