73 lines
1.8 KiB
Markdown
73 lines
1.8 KiB
Markdown
# DAL Layer
|
|
|
|
Set up Entity Framework Core and repositories.
|
|
|
|
## DbContext
|
|
|
|
```csharp
|
|
// OrderManagement.Infrastructure/Data/OrderDbContext.cs
|
|
using Microsoft.EntityFrameworkCore;
|
|
using OrderManagement.Domain.Entities;
|
|
|
|
public class OrderDbContext : DbContext
|
|
{
|
|
public DbSet<Order> Orders => Set<Order>();
|
|
|
|
public OrderDbContext(DbContextOptions<OrderDbContext> options) : base(options) { }
|
|
|
|
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
|
{
|
|
modelBuilder.Entity<Order>(entity =>
|
|
{
|
|
entity.HasKey(e => e.Id);
|
|
entity.Property(e => e.TotalAmount).HasPrecision(18, 2);
|
|
entity.OwnsMany(e => e.Items, items =>
|
|
{
|
|
items.Property(i => i.Price).HasPrecision(18, 2);
|
|
});
|
|
});
|
|
}
|
|
}
|
|
```
|
|
|
|
## Repository
|
|
|
|
```csharp
|
|
// OrderManagement.Infrastructure/Repositories/OrderRepository.cs
|
|
public interface IOrderRepository
|
|
{
|
|
Task<Order> GetByIdAsync(int id, CancellationToken ct);
|
|
Task AddAsync(Order order, CancellationToken ct);
|
|
Task SaveChangesAsync(CancellationToken ct);
|
|
}
|
|
|
|
public class OrderRepository : IOrderRepository
|
|
{
|
|
private readonly OrderDbContext _context;
|
|
|
|
public OrderRepository(OrderDbContext context) => _context = context;
|
|
|
|
public async Task<Order> GetByIdAsync(int id, CancellationToken ct)
|
|
{
|
|
return await _context.Orders
|
|
.Include(o => o.Items)
|
|
.FirstOrDefaultAsync(o => o.Id == id, ct)
|
|
?? throw new KeyNotFoundException($"Order {id} not found");
|
|
}
|
|
|
|
public async Task AddAsync(Order order, CancellationToken ct)
|
|
{
|
|
await _context.Orders.AddAsync(order, ct);
|
|
}
|
|
|
|
public async Task SaveChangesAsync(CancellationToken ct)
|
|
{
|
|
await _context.SaveChangesAsync(ct);
|
|
}
|
|
}
|
|
```
|
|
|
|
## Next Steps
|
|
|
|
Continue to [API Layer](05-api-layer.md)
|