Я создаю проект с использованием 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();
}
}
Тема.Core
Entities
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();
}`