使用Entity Framework Core(EF Core)进行开发时,结合仓库模式和工作单元模式,服务层以及控制器,可以实现一个清晰和高效的架构
- 仓储(Repository)
仓储模式封装对数据源的访问逻辑,包括CRUD操作。以下是一个简单的仓储接口和实现示例:
public interface IRepository
{
Task<IEnumerable
Task
Task AddAsync(T entity);
Task UpdateAsync(T entity);
Task DeleteAsync(int id);
}
public class Repository
{
private readonly DbContext _context;
private readonly DbSet
public Repository(DbContext context) { _context = context; _dbSet = context.Set<T>(); } public async Task<IEnumerable<T>> GetAllAsync() => await _dbSet.ToListAsync(); public async Task<T> GetByIdAsync(int id) => await _dbSet.FindAsync(id); public async Task AddAsync(T entity) => await _dbSet.AddAsync(entity); public async Task UpdateAsync(T entity) => _dbSet.Update(entity); public async Task DeleteAsync(int id) { var entity = await GetByIdAsync(id); if (entity != null) { _dbSet.Remove(entity); } }
}
CopyInsert
2. 工作单元(Unit of Work)
工作单元职责是协调多个仓储之间的操作,并统一提交事务。以下是一个工作单元的接口和实现示例:
public interface IUnitOfWork : IDisposable
{
IRepository
Task
}
public class UnitOfWork : IUnitOfWork
{
private readonly DbContext _context;
public UnitOfWork(DbContext context) { _context = context; } public IRepository<TEntity> Repository<TEntity>() where TEntity : class { return new Repository<TEntity>(_context); } public async Task<int> SaveChangesAsync() => await _context.SaveChangesAsync(); public void Dispose() { _context.Dispose(); }
}
CopyInsert
3. 服务层(Service Layer)
服务层处理业务逻辑,并调用仓储和工作单元。以下是服务层的示例:
public interface IMyService
{
Task<IEnumerable
Task
Task AddEntityAsync(MyEntity entity);
Task UpdateEntityAsync(MyEntity entity);
Task DeleteEntityAsync(int id);
}
public class MyService : IMyService
{
private readonly IUnitOfWork _unitOfWork;
public MyService(IUnitOfWork unitOfWork) { _unitOfWork = unitOfWork; } public async Task<IEnumerable<MyEntity>> GetAllEntitiesAsync() { return await _unitOfWork.Repository<MyEntity>().GetAllAsync(); } public async Task<MyEntity> GetEntityByIdAsync(int id) { return await _unitOfWork.Repository<MyEntity>().GetByIdAsync(id); } public async Task AddEntityAsync(MyEntity entity) { await _unitOfWork.Repository<MyEntity>().AddAsync(entity); await _unitOfWork.SaveChangesAsync(); } public async Task UpdateEntityAsync(MyEntity entity) { await _unitOfWork.Repository<MyEntity>().UpdateAsync(entity); await _unitOfWork.SaveChangesAsync(); } public async Task DeleteEntityAsync(int id) { await _unitOfWork.Repository<MyEntity>().DeleteAsync(id); await _unitOfWork.SaveChangesAsync(); }
}
CopyInsert
4. 控制器(Controller)
控制器接收用户请求并调用服务层。以下是控制器的示例:
[ApiController]
[Route("[controller]")]
public class MyEntityController : ControllerBase
{
private readonly IMyService _myService;
public MyEntityController(IMyService myService) { _myService = myService; } [HttpGet] public async Task<IActionResult> GetAll() { var entities = await _myService.GetAllEntitiesAsync(); return Ok(entities); } [HttpGet("{id}")] public async Task<IActionResult> Get(int id) { var entity = await _myService.GetEntityByIdAsync(id); if (entity == null) return NotFound(); return Ok(entity); } [HttpPost] public async Task<IActionResult> Post([FromBody] MyEntity entity) { await _myService.AddEntityAsync(entity); return CreatedAtAction(nameof(Get), new { id = entity.Id }, entity); } [HttpPut("{id}")] public async Task<IActionResult> Put(int id, [FromBody] MyEntity entity) { if (id != entity.Id) return BadRequest(); await _myService.UpdateEntityAsync(entity); return NoContent(); } [HttpDelete("{id}")] public async Task<IActionResult> Delete(int id) { await _myService.DeleteEntityAsync(id); return NoContent(); }
}
CopyInsert
总结
通过结合使用仓储、工作单元、服务层和控制器,可以构建一个高内聚、低耦合的分层架构。这种设计有助于增强代码的可读性、可维护性和可扩展性。在实际开发中,可以根据团队和项目的需求进行适当的调整和优化。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!