
Introducción
Trabajar con .NET y Entity Framework Core te lleva inevitablemente a uno de los temas más debatidos de la comunidad: ¿deberías usar el Repository Pattern, o trabajar directamente con el DbContext? Las opiniones varían enormemente, y puede ser difícil decidir qué enfoque es el adecuado para tu aplicación.
En este artículo te guiaré por ambas opciones con ejemplos prácticos, explicaciones claras y contexto del mundo real. Exploraremos sus ventajas, inconvenientes, diferencias de rendimiento y en qué casos cada enfoque realmente brilla. Al final, podrás tomar una decisión informada y pragmática que se ajuste a las necesidades de tus proyectos .NET, sin complejidad innecesaria ni over-engineering.
⸻
Tabla de Contenidos
- Entendiendo el Repository Pattern
- El Enfoque Directo con EF Core
- El Caso A FAVOR del Repository Pattern
- El Caso EN CONTRA del Repository Pattern
- Comparación de Rendimiento
- Escenarios del Mundo Real
- Mi Recomendación
- Buenas Prácticas
Entendiendo el Repository Pattern
El Repository Pattern es un patrón de diseño que crea una capa de abstracción entre tu lógica de negocio y la lógica de acceso a datos. Encapsula la lógica necesaria para acceder a las fuentes de datos.
Implementación Básica de un Repositorio
// Interfaz de repositorio genérica
public interface IRepository<T> where T : class
{
Task<T?> GetByIdAsync(int id);
Task<IEnumerable<T>> GetAllAsync();
Task<T> AddAsync(T entity);
Task UpdateAsync(T entity);
Task DeleteAsync(int id);
Task<IEnumerable<T>> FindAsync(Expression<Func<T, bool>> predicate);
}
// Implementación de repositorio genérico
public class Repository<T> : IRepository<T> where T : class
{
private readonly ApplicationDbContext _context;
private readonly DbSet<T> _dbSet;
public Repository(ApplicationDbContext context)
{
_context = context;
_dbSet = context.Set<T>();
}
public async Task<T?> GetByIdAsync(int id)
{
return await _dbSet.FindAsync(id);
}
public async Task<IEnumerable<T>> GetAllAsync()
{
return await _dbSet.ToListAsync();
}
public async Task<T> AddAsync(T entity)
{
await _dbSet.AddAsync(entity);
await _context.SaveChangesAsync();
return entity;
}
public async Task UpdateAsync(T entity)
{
_dbSet.Update(entity);
await _context.SaveChangesAsync();
}
public async Task DeleteAsync(int id)
{
var entity = await GetByIdAsync(id);
if (entity != null)
{
_dbSet.Remove(entity);
await _context.SaveChangesAsync();
}
}
public async Task<IEnumerable<T>> FindAsync(Expression<Func<T, bool>> predicate)
{
return await _dbSet.Where(predicate).ToListAsync();
}
}
Repositorio Específico para Consultas Complejas
public interface IOrderRepository : IRepository<Order>
{
Task<IEnumerable<Order>> GetOrdersByCustomerIdAsync(int customerId);
Task<IEnumerable<Order>> GetPendingOrdersAsync();
Task<decimal> GetTotalRevenueByDateRangeAsync(DateTime start, DateTime end);
}
public class OrderRepository : Repository<Order>, IOrderRepository
{
private readonly ApplicationDbContext _context;
public OrderRepository(ApplicationDbContext context) : base(context)
{
_context = context;
}
public async Task<IEnumerable<Order>> GetOrdersByCustomerIdAsync(int customerId)
{
return await _context.Orders
.Include(o => o.OrderItems)
.ThenInclude(oi => oi.Product)
.Where(o => o.CustomerId == customerId)
.OrderByDescending(o => o.OrderDate)
.ToListAsync();
}
public async Task<IEnumerable<Order>> GetPendingOrdersAsync()
{
return await _context.Orders
.Include(o => o.Customer)
.Where(o => o.Status == OrderStatus.Pending)
.ToListAsync();
}
public async Task<decimal> GetTotalRevenueByDateRangeAsync(DateTime start, DateTime end)
{
return await _context.Orders
.Where(o => o.OrderDate >= start && o.OrderDate <= end)
.SumAsync(o => o.TotalAmount);
}
}
Uso en la Capa de Servicio
public class OrderService
{
private readonly IOrderRepository _orderRepository;
public OrderService(IOrderRepository orderRepository)
{
_orderRepository = orderRepository;
}
public async Task<OrderDto> CreateOrderAsync(CreateOrderDto dto)
{
var order = new Order
{
CustomerId = dto.CustomerId,
OrderDate = DateTime.UtcNow,
Status = OrderStatus.Pending,
TotalAmount = dto.TotalAmount
};
var createdOrder = await _orderRepository.AddAsync(order);
return MapToDto(createdOrder);
}
public async Task<IEnumerable<OrderDto>> GetCustomerOrdersAsync(int customerId)
{
var orders = await _orderRepository.GetOrdersByCustomerIdAsync(customerId);
return orders.Select(MapToDto);
}
}
El Enfoque Directo con EF Core
El enfoque directo significa usar el DbContext directamente en tus servicios sin una capa de abstracción.
Servicio con DbContext Directo
public class OrderService
{
private readonly ApplicationDbContext _context;
public OrderService(ApplicationDbContext context)
{
_context = context;
}
public async Task<OrderDto> CreateOrderAsync(CreateOrderDto dto)
{
var order = new Order
{
CustomerId = dto.CustomerId,
OrderDate = DateTime.UtcNow,
Status = OrderStatus.Pending,
TotalAmount = dto.TotalAmount
};
_context.Orders.Add(order);
await _context.SaveChangesAsync();
return MapToDto(order);
}
public async Task<IEnumerable<OrderDto>> GetCustomerOrdersAsync(int customerId)
{
var orders = await _context.Orders
.Include(o => o.OrderItems)
.ThenInclude(oi => oi.Product)
.Where(o => o.CustomerId == customerId)
.OrderByDescending(o => o.OrderDate)
.ToListAsync();
return orders.Select(MapToDto);
}
public async Task<IEnumerable<OrderDto>> GetPendingOrdersAsync()
{
return await _context.Orders
.Include(o => o.Customer)
.Where(o => o.Status == OrderStatus.Pending)
.Select(o => new OrderDto
{
Id = o.Id,
CustomerName = o.Customer.Name,
OrderDate = o.OrderDate,
Status = o.Status.ToString(),
TotalAmount = o.TotalAmount
})
.ToListAsync();
}
public async Task<decimal> GetTotalRevenueByDateRangeAsync(DateTime start, DateTime end)
{
return await _context.Orders
.Where(o => o.OrderDate >= start && o.OrderDate <= end)
.SumAsync(o => o.TotalAmount);
}
}
El Caso A FAVOR del Repository Pattern
1. Testabilidad
El Repository Pattern facilita las pruebas unitarias al permitir mockear el repositorio:
public class OrderServiceTests
{
[Fact]
public async Task CreateOrder_ShouldReturnOrderDto()
{
// Arrange
var mockRepository = new Mock<IOrderRepository>();
var expectedOrder = new Order { Id = 1, CustomerId = 1 };
mockRepository
.Setup(r => r.AddAsync(It.IsAny<Order>()))
.ReturnsAsync(expectedOrder);
var service = new OrderService(mockRepository.Object);
var dto = new CreateOrderDto { CustomerId = 1, TotalAmount = 100 };
// Act
var result = await service.CreateOrderAsync(dto);
// Assert
Assert.NotNull(result);
mockRepository.Verify(r => r.AddAsync(It.IsAny<Order>()), Times.Once);
}
}
2. Separación de Responsabilidades
Separación clara entre la lógica de negocio y el acceso a datos:
// Capa de lógica de negocio
public class OrderProcessingService
{
private readonly IOrderRepository _orderRepository;
private readonly IPaymentService _paymentService;
private readonly IEmailService _emailService;
public OrderProcessingService(
IOrderRepository orderRepository,
IPaymentService paymentService,
IEmailService emailService)
{
_orderRepository = orderRepository;
_paymentService = paymentService;
_emailService = emailService;
}
public async Task<bool> ProcessOrderAsync(int orderId)
{
// Lógica de negocio aquí - limpia y enfocada
var order = await _orderRepository.GetByIdAsync(orderId);
if (order == null) return false;
var paymentResult = await _paymentService.ProcessPaymentAsync(order);
if (!paymentResult.Success) return false;
order.Status = OrderStatus.Paid;
await _orderRepository.UpdateAsync(order);
await _emailService.SendOrderConfirmationAsync(order);
return true;
}
}
3. Lógica de Acceso a Datos Centralizada
Todas las consultas a la base de datos en un solo lugar, lo que facilita el mantenimiento:
public class ProductRepository : Repository<Product>, IProductRepository
{
private readonly ApplicationDbContext _context;
public ProductRepository(ApplicationDbContext context) : base(context)
{
_context = context;
}
// Consulta compleja centralizada
public async Task<IEnumerable<Product>> GetActiveProductsWithStockAsync()
{
return await _context.Products
.Include(p => p.Category)
.Include(p => p.Supplier)
.Where(p => p.IsActive && p.Stock > 0)
.OrderBy(p => p.Name)
.ToListAsync();
}
// Si la lógica de la consulta cambia, solo la actualizas aquí
public async Task<IEnumerable<Product>> GetLowStockProductsAsync(int threshold = 10)
{
return await _context.Products
.Where(p => p.IsActive && p.Stock <= threshold)
.Include(p => p.Supplier)
.ToListAsync();
}
}
4. Independencia del Proveedor de Base de Datos
Más fácil cambiar entre diferentes fuentes de datos:
// La interfaz permanece igual
public interface ICustomerRepository
{
Task<Customer?> GetByEmailAsync(string email);
Task<IEnumerable<Customer>> GetActiveCustomersAsync();
}
// Implementación para SQL Server
public class SqlServerCustomerRepository : ICustomerRepository
{
private readonly ApplicationDbContext _context;
public async Task<Customer?> GetByEmailAsync(string email)
{
return await _context.Customers
.FirstOrDefaultAsync(c => c.Email == email);
}
public async Task<IEnumerable<Customer>> GetActiveCustomersAsync()
{
return await _context.Customers
.Where(c => c.IsActive)
.ToListAsync();
}
}
// Implementación para MongoDB (hipotética)
public class MongoCustomerRepository : ICustomerRepository
{
private readonly IMongoCollection<Customer> _collection;
public async Task<Customer?> GetByEmailAsync(string email)
{
return await _collection
.Find(c => c.Email == email)
.FirstOrDefaultAsync();
}
public async Task<IEnumerable<Customer>> GetActiveCustomersAsync()
{
return await _collection
.Find(c => c.IsActive)
.ToListAsync();
}
}
El Caso EN CONTRA del Repository Pattern
1. EF Core Ya Es un Repository Pattern
El DbContext y el DbSet ya implementan los patrones Repository y Unit of Work:
// El DbContext ES una Unit of Work
public class ApplicationDbContext : DbContext
{
// El DbSet<T> ES un Repository
public DbSet<Order> Orders { get; set; }
public DbSet<Customer> Customers { get; set; }
public DbSet<Product> Products { get; set; }
// SaveChanges gestiona la transacción
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
{
return await base.SaveChangesAsync(cancellationToken);
}
}
2. Sobre-Abstracción y Complejidad Innecesaria
Añadir una capa de repositorio puede crear una indirección innecesaria:
// Con Repository: 3 capas de indirección
Controller -> Service -> Repository -> DbContext
// EF Core directo: 2 capas
Controller -> Service (con DbContext)
// Ejemplo de sobre-abstracción
public class CustomerRepository : ICustomerRepository
{
private readonly ApplicationDbContext _context;
// Este método literalmente solo envuelve al DbContext
public async Task<Customer?> GetByIdAsync(int id)
{
return await _context.Customers.FindAsync(id); // Envoltorio sin sentido
}
}
3. Pérdida de Funcionalidades Potentes de EF Core
Los repositorios pueden ocultar funcionalidades potentes de EF Core:
// EF Core directo - Todo el poder de IQueryable
public async Task<PagedResult<ProductDto>> GetProductsAsync(ProductFilter filter)
{
IQueryable<Product> query = _context.Products
.Include(p => p.Category)
.AsQueryable();
// Filtrado dinámico
if (!string.IsNullOrEmpty(filter.CategoryName))
query = query.Where(p => p.Category.Name == filter.CategoryName);
if (filter.MinPrice.HasValue)
query = query.Where(p => p.Price >= filter.MinPrice.Value);
if (filter.MaxPrice.HasValue)
query = query.Where(p => p.Price <= filter.MaxPrice.Value);
// Proyección eficiente - solo selecciona las columnas necesarias
var pagedQuery = query
.OrderBy(p => p.Name)
.Skip((filter.Page - 1) * filter.PageSize)
.Take(filter.PageSize)
.Select(p => new ProductDto
{
Id = p.Id,
Name = p.Name,
Price = p.Price,
CategoryName = p.Category.Name
});
var items = await pagedQuery.ToListAsync();
var totalCount = await query.CountAsync();
return new PagedResult<ProductDto>
{
Items = items,
TotalCount = totalCount,
Page = filter.Page,
PageSize = filter.PageSize
};
}
// Con Repository - Tendrías que exponer IQueryable o crear infinidad de métodos
public interface IProductRepository
{
IQueryable<Product> GetQueryable(); // Abstracción con fugas
// O
Task<IEnumerable<Product>> GetByCategoryAsync(string category);
Task<IEnumerable<Product>> GetByPriceRangeAsync(decimal min, decimal max);
Task<IEnumerable<Product>> GetByCategoryAndPriceAsync(string category, decimal min, decimal max);
// ... combinaciones infinitas
}
4. Probar EF Core Es Más Fácil de Lo Que Piensas
Con el proveedor InMemory o SQLite, probar es sencillo:
public class OrderServiceTests
{
private ApplicationDbContext CreateDbContext()
{
var options = new DbContextOptionsBuilder<ApplicationDbContext>()
.UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
.Options;
return new ApplicationDbContext(options);
}
[Fact]
public async Task GetPendingOrders_ShouldReturnOnlyPendingOrders()
{
// Arrange
await using var context = CreateDbContext();
context.Orders.AddRange(
new Order { Id = 1, Status = OrderStatus.Pending },
new Order { Id = 2, Status = OrderStatus.Completed },
new Order { Id = 3, Status = OrderStatus.Pending }
);
await context.SaveChangesAsync();
var service = new OrderService(context);
// Act
var result = await service.GetPendingOrdersAsync();
// Assert
Assert.Equal(2, result.Count());
Assert.All(result, o => Assert.Equal("Pending", o.Status));
}
}
5. Sobrecarga de Rendimiento
Cada abstracción añade sobrecarga:
// Enfoque con Repository - Múltiples capas de ejecución
var orders = await _orderRepository.GetOrdersByCustomerIdAsync(customerId);
// Ejecución: Controller -> Service -> Repository -> DbContext -> Base de datos
// DbContext directo - Menos capas
var orders = await _context.Orders
.Where(o => o.CustomerId == customerId)
.ToListAsync();
// Ejecución: Controller -> Service (DbContext) -> Base de datos
Comparación de Rendimiento
Veamos un benchmark real comparando ambos enfoques:
[MemoryDiagnoser]
public class RepositoryVsDirectBenchmark
{
private ApplicationDbContext _context;
private IOrderRepository _repository;
[GlobalSetup]
public void Setup()
{
var options = new DbContextOptionsBuilder<ApplicationDbContext>()
.UseInMemoryDatabase("BenchmarkDb")
.Options;
_context = new ApplicationDbContext(options);
_repository = new OrderRepository(_context);
// Datos iniciales (seed)
for (int i = 1; i <= 1000; i++)
{
_context.Orders.Add(new Order
{
Id = i,
CustomerId = i % 100,
OrderDate = DateTime.UtcNow.AddDays(-i),
TotalAmount = i * 10
});
}
_context.SaveChanges();
}
[Benchmark]
public async Task<int> WithRepository()
{
var orders = await _repository.FindAsync(o => o.CustomerId == 50);
return orders.Count();
}
[Benchmark]
public async Task<int> WithDirectDbContext()
{
var orders = await _context.Orders
.Where(o => o.CustomerId == 50)
.ToListAsync();
return orders.Count;
}
[Benchmark]
public async Task<int> WithDirectDbContext_Projection()
{
// Más eficiente - solo selecciona los datos necesarios
return await _context.Orders
.Where(o => o.CustomerId == 50)
.CountAsync();
}
}
/*
Resultados (típicos):
| Method | Mean | Error | StdDev | Gen 0 | Allocated |
|------------------------------ |---------:|--------:|--------:|-------:|----------:|
| WithRepository | 125.4 μs | 2.1 μs | 1.9 μs | 2.4414 | 15.6 KB |
| WithDirectDbContext | 118.2 μs | 1.8 μs | 1.6 μs | 2.1973 | 14.2 KB |
| WithDirectDbContext_Projection| 95.3 μs | 1.2 μs | 1.1 μs | 0.9766 | 6.1 KB |
*/
Escenarios del Mundo Real
Escenario 1: Aplicación CRUD Simple
Mejor Opción: EF Core Directo
// Para un blog simple o una app de tareas, los repositorios añaden complejidad innecesaria
public class BlogPostService
{
private readonly ApplicationDbContext _context;
public BlogPostService(ApplicationDbContext context)
{
_context = context;
}
public async Task<IEnumerable<BlogPostDto>> GetRecentPostsAsync(int count = 10)
{
return await _context.BlogPosts
.Include(p => p.Author)
.Include(p => p.Category)
.Where(p => p.IsPublished)
.OrderByDescending(p => p.PublishedDate)
.Take(count)
.Select(p => new BlogPostDto
{
Id = p.Id,
Title = p.Title,
Excerpt = p.Content.Substring(0, 200),
AuthorName = p.Author.Name,
CategoryName = p.Category.Name,
PublishedDate = p.PublishedDate
})
.ToListAsync();
}
}
Escenario 2: Aplicación Empresarial Compleja
Mejor Opción: Repository Pattern (con matices)
// Múltiples equipos, lógica de negocio compleja, necesidad de abstracción
public interface IOrderRepository
{
Task<Order?> GetOrderWithDetailsAsync(int orderId);
Task<IEnumerable<Order>> GetOrdersByStatusAsync(OrderStatus status);
Task<OrderStatistics> GetOrderStatisticsAsync(DateTime from, DateTime to);
}
public class OrderProcessingService
{
private readonly IOrderRepository _orderRepository;
private readonly IPaymentRepository _paymentRepository;
private readonly IInventoryRepository _inventoryRepository;
private readonly INotificationService _notificationService;
public OrderProcessingService(
IOrderRepository orderRepository,
IPaymentRepository paymentRepository,
IInventoryRepository inventoryRepository,
INotificationService notificationService)
{
_orderRepository = orderRepository;
_paymentRepository = paymentRepository;
_inventoryRepository = inventoryRepository;
_notificationService = notificationService;
}
public async Task<ProcessOrderResult> ProcessOrderAsync(int orderId)
{
var order = await _orderRepository.GetOrderWithDetailsAsync(orderId);
if (order == null)
return ProcessOrderResult.NotFound();
// Lógica de negocio compleja que coordina múltiples repositorios
var inventoryCheck = await _inventoryRepository.CheckAvailabilityAsync(order.OrderItems);
if (!inventoryCheck.AllAvailable)
return ProcessOrderResult.InsufficientInventory(inventoryCheck.UnavailableItems);
var payment = await _paymentRepository.ProcessPaymentAsync(order);
if (!payment.Success)
return ProcessOrderResult.PaymentFailed(payment.ErrorMessage);
await _inventoryRepository.ReserveItemsAsync(order.OrderItems);
order.Status = OrderStatus.Processing;
await _orderRepository.UpdateAsync(order);
await _notificationService.SendOrderConfirmationAsync(order);
return ProcessOrderResult.Success(order);
}
}
Escenario 3: Arquitectura de Microservicios
Mejor Opción: Enfoque Híbrido
// Usa repositorios para preocupaciones transversales, DbContext directo para consultas simples
public class OrderService
{
private readonly ApplicationDbContext _context;
private readonly ICacheRepository _cacheRepository;
private readonly IAuditRepository _auditRepository;
public OrderService(
ApplicationDbContext context,
ICacheRepository cacheRepository,
IAuditRepository auditRepository)
{
_context = context;
_cacheRepository = cacheRepository;
_auditRepository = auditRepository;
}
public async Task<OrderDto?> GetOrderAsync(int orderId)
{
// Primero revisa la caché (repositorio para preocupación transversal)
var cached = await _cacheRepository.GetAsync<OrderDto>($"order:{orderId}");
if (cached != null)
return cached;
// DbContext directo para acceso a datos
var order = await _context.Orders
.Include(o => o.Customer)
.Include(o => o.OrderItems)
.FirstOrDefaultAsync(o => o.Id == orderId);
if (order == null)
return null;
var dto = MapToDto(order);
// Cachea el resultado
await _cacheRepository.SetAsync($"order:{orderId}", dto, TimeSpan.FromMinutes(10));
return dto;
}
public async Task<Order> CreateOrderAsync(CreateOrderDto createDto)
{
var order = MapToOrder(createDto);
_context.Orders.Add(order);
await _context.SaveChangesAsync();
// Registro de auditoría a través del repositorio
await _auditRepository.LogAsync(new AuditEntry
{
EntityType = nameof(Order),
EntityId = order.Id.ToString(),
Action = "Create",
Timestamp = DateTime.UtcNow
});
return order;
}
}
Mi Recomendación: El Enfoque Pragmático
Después de años trabajando con ambos enfoques, esta es mi opinión:
Usa EF Core Directo Cuando:
- Aplicaciones simples - operaciones CRUD, equipos pequeños
- Prototipos o MVPs - la velocidad de desarrollo importa más
- Operaciones intensivas en lectura - necesitas todo el poder de IQueryable
- El rendimiento es crítico - cada capa añade sobrecarga
- Equipo pequeño - todos entienden bien EF Core
// Simple, limpio, efectivo
public class ProductService
{
private readonly ApplicationDbContext _context;
public ProductService(ApplicationDbContext context)
{
_context = context;
}
public async Task<IEnumerable<ProductDto>> SearchProductsAsync(string searchTerm)
{
return await _context.Products
.Where(p => p.Name.Contains(searchTerm) || p.Description.Contains(searchTerm))
.Select(p => new ProductDto
{
Id = p.Id,
Name = p.Name,
Price = p.Price
})
.ToListAsync();
}
}
Usa el Repository Pattern Cuando:
- Lógica de negocio compleja - múltiples fuentes de datos, transacciones complejas
- Equipos grandes - necesitan límites y contratos claros
- Múltiples fuentes de datos - SQL + NoSQL + APIs externas
- Requisitos exigentes de testing - necesidad de mockear fácilmente la capa de datos
- Domain-Driven Design - siguiendo los principios de DDD
// Abstracción clara para escenarios complejos
public interface IOrderRepository
{
Task<Order?> GetByIdWithFullDetailsAsync(int orderId);
Task<IEnumerable<Order>> GetOrdersRequiringAttentionAsync();
Task<bool> CanFulfillOrderAsync(Order order);
}
public class OrderRepository : IOrderRepository
{
private readonly ApplicationDbContext _context;
private readonly IInventoryService _inventoryService;
public async Task<bool> CanFulfillOrderAsync(Order order)
{
// Lógica compleja que combina consultas a la base de datos y llamadas a servicios externos
var items = await _context.OrderItems
.Where(oi => oi.OrderId == order.Id)
.Include(oi => oi.Product)
.ToListAsync();
foreach (var item in items)
{
var available = await _inventoryService.CheckStockAsync(item.ProductId, item.Quantity);
if (!available)
return false;
}
return true;
}
}
El Enfoque Híbrido (Mi Favorito)
// Usa repositorios SOLO cuando aportan valor
public class OrderService
{
private readonly ApplicationDbContext _context;
private readonly ISpecificationEvaluator _specificationEvaluator;
public OrderService(ApplicationDbContext context, ISpecificationEvaluator specificationEvaluator)
{
_context = context;
_specificationEvaluator = specificationEvaluator;
}
// Consultas simples: DbContext directo
public async Task<Order?> GetOrderByIdAsync(int id)
{
return await _context.Orders
.Include(o => o.Customer)
.FirstOrDefaultAsync(o => o.Id == id);
}
// Consultas complejas: usa el Specification Pattern (abstracción ligera)
public async Task<IEnumerable<Order>> GetOrdersAsync(ISpecification<Order> specification)
{
return await _specificationEvaluator
.GetQuery(_context.Orders, specification)
.ToListAsync();
}
}
// Specification Pattern - lógica de consulta reutilizable sin un repositorio completo
public class OrdersWithItemsSpecification : Specification<Order>
{
public OrdersWithItemsSpecification(int customerId)
{
AddInclude(o => o.OrderItems);
AddInclude("OrderItems.Product");
AddCriteria(o => o.CustomerId == customerId);
ApplyOrderByDescending(o => o.OrderDate);
}
}
Buenas Prácticas
1. No Filtres IQueryable Desde los Repositorios
// MAL - Abstracción con fugas
public interface IProductRepository
{
IQueryable<Product> GetAll();
}
// BIEN - Consulta encapsulada
public interface IProductRepository
{
Task<IEnumerable<Product>> GetActiveProductsAsync();
Task<IEnumerable<Product>> SearchAsync(string searchTerm);
}
2. Usa Specifications para Consultas Complejas
public interface ISpecification<T>
{
Expression<Func<T, bool>>? Criteria { get; }
List<Expression<Func<T, object>>> Includes { get; }
List<string> IncludeStrings { get; }
}
public class ActiveProductsWithCategorySpecification : ISpecification<Product>
{
public Expression<Func<Product, bool>> Criteria => p => p.IsActive;
public List<Expression<Func<Product, object>>> Includes { get; } = new()
{
p => p.Category
};
public List<string> IncludeStrings { get; } = new();
}
3. Evita Repositorios Genéricos para Todo
// MAL - Repositorio genérico intentando hacerlo todo
public class Repository<T> : IRepository<T> where T : class
{
// Más de 50 métodos intentando cubrir todos los escenarios posibles
}
// BIEN - Repositorios específicos para necesidades específicas
public interface IOrderRepository
{
Task<Order?> GetByIdAsync(int id);
Task<IEnumerable<Order>> GetPendingOrdersAsync();
Task<OrderStatistics> GetStatisticsAsync(DateTime from, DateTime to);
// Solo los métodos que realmente necesitas
}
4. Considera Usar MediatR para Operaciones Complejas
// Separación limpia sin una capa de repositorio pesada
public class GetOrderByIdQuery : IRequest<OrderDto?>
{
public int OrderId { get; set; }
}
public class GetOrderByIdQueryHandler : IRequestHandler<GetOrderByIdQuery, OrderDto?>
{
private readonly ApplicationDbContext _context;
public GetOrderByIdQueryHandler(ApplicationDbContext context)
{
_context = context;
}
public async Task<OrderDto?> Handle(GetOrderByIdQuery request, CancellationToken cancellationToken)
{
return await _context.Orders
.Include(o => o.Customer)
.Where(o => o.Id == request.OrderId)
.Select(o => new OrderDto
{
Id = o.Id,
CustomerName = o.Customer.Name,
TotalAmount = o.TotalAmount
})
.FirstOrDefaultAsync(cancellationToken);
}
}
Conclusión
No hay una respuesta universal al debate Repository vs EF Core Directo. El mejor enfoque depende de tu escenario específico:
- Proyectos pequeños, CRUD simple: EF Core directo es más limpio y rápido
- Aplicaciones empresariales grandes: el Repository Pattern aporta estructura
- La mayoría de las aplicaciones reales: un enfoque híbrido funciona mejor
Mi consejo: empieza simple con el DbContext directo. Añade repositorios solo cuando realmente necesites la abstracción. No sobre-ingenieres prematuramente, pero no tengas miedo de refactorizar cuando la complejidad lo exija.
Recuerda: EF Core ya está bien diseñado. Respeta sus patrones y abstrae solo cuando estés añadiendo valor real, no solo capas.
¿Qué enfoque prefieres? ¡Cuéntamelo en los comentarios!
Lecturas Adicionales:

