94 lines
3.2 KiB
C#
94 lines
3.2 KiB
C#
// src/Webshop.Infrastructure/Repositories/DiscountRepository.cs
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Webshop.Domain.Entities;
|
|
using Webshop.Domain.Interfaces;
|
|
using Webshop.Infrastructure.Data;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace Webshop.Infrastructure.Repositories
|
|
{
|
|
public class DiscountRepository : IDiscountRepository
|
|
{
|
|
private readonly ApplicationDbContext _context;
|
|
|
|
public DiscountRepository(ApplicationDbContext context)
|
|
{
|
|
_context = context;
|
|
}
|
|
|
|
public async Task<IEnumerable<Discount>> GetAllAsync()
|
|
{
|
|
return await _context.Discounts
|
|
.Include(d => d.ProductDiscounts)
|
|
.Include(d => d.categorieDiscounts)
|
|
.OrderBy(d => d.Name)
|
|
.ToListAsync();
|
|
}
|
|
|
|
public async Task<Discount?> GetByIdAsync(Guid id)
|
|
{
|
|
return await _context.Discounts
|
|
.Include(d => d.ProductDiscounts)
|
|
.Include(d => d.categorieDiscounts)
|
|
.FirstOrDefaultAsync(d => d.Id == id);
|
|
}
|
|
|
|
// << NEUE METHODE IMPLEMENTIEREN >>
|
|
public async Task<Discount?> GetByCouponCodeAsync(string couponCode)
|
|
{
|
|
// Case-insensitive Suche für den Gutscheincode
|
|
return await _context.Discounts
|
|
.Include(d => d.ProductDiscounts)
|
|
.Include(d => d.categorieDiscounts)
|
|
.FirstOrDefaultAsync(d => d.CouponCode != null && d.CouponCode.ToUpper() == couponCode.ToUpper());
|
|
}
|
|
// << ENDE DER NEUEN METHODE >>
|
|
|
|
public async Task AddAsync(Discount discount)
|
|
{
|
|
await _context.Discounts.AddAsync(discount);
|
|
await _context.SaveChangesAsync();
|
|
}
|
|
|
|
public async Task UpdateAsync(Discount discount)
|
|
{
|
|
// Sicherstellen, dass die verknüpften Entitäten nicht neu hinzugefügt werden
|
|
var existingDiscount = await _context.Discounts
|
|
.Include(d => d.ProductDiscounts)
|
|
.Include(d => d.categorieDiscounts)
|
|
.FirstOrDefaultAsync(d => d.Id == discount.Id);
|
|
|
|
if (existingDiscount != null)
|
|
{
|
|
_context.Entry(existingDiscount).CurrentValues.SetValues(discount);
|
|
|
|
// Manuelles Synchronisieren der Many-to-Many-Beziehungen
|
|
existingDiscount.ProductDiscounts.Clear();
|
|
foreach (var pd in discount.ProductDiscounts)
|
|
{
|
|
existingDiscount.ProductDiscounts.Add(pd);
|
|
}
|
|
|
|
existingDiscount.categorieDiscounts.Clear();
|
|
foreach (var cd in discount.categorieDiscounts)
|
|
{
|
|
existingDiscount.categorieDiscounts.Add(cd);
|
|
}
|
|
|
|
await _context.SaveChangesAsync();
|
|
}
|
|
}
|
|
|
|
public async Task DeleteAsync(Guid id)
|
|
{
|
|
var discount = await _context.Discounts.FindAsync(id);
|
|
if (discount != null)
|
|
{
|
|
_context.Discounts.Remove(discount);
|
|
await _context.SaveChangesAsync();
|
|
}
|
|
}
|
|
}
|
|
} |