Files
ShopSolution-backend/Webshop.Infrastructure/Repositories/ProductRepository.cs
Tizian.Breuch 3f1874f7c2
All checks were successful
Branch - test - Build and Push Backend API Docker Image / build-and-push (push) Successful in 22s
test upload bild
2025-11-07 10:30:52 +01:00

73 lines
2.5 KiB
C#

// src/Webshop.Infrastructure/Repositories/ProductRepository.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 ProductRepository : IProductRepository // Implementiert das korrigierte Interface
{
private readonly ApplicationDbContext _context;
public ProductRepository(ApplicationDbContext context)
{
_context = context;
}
public async Task<IEnumerable<Product>> GetAllProductsAsync()
{
return await _context.Products.ToListAsync();
}
public async Task<Product?> GetProductByIdAsync(Guid id)
{
return await _context.Products.FindAsync(id);
}
public async Task<Product?> GetBySlugAsync(string slug)
{
return await _context.Products.FirstOrDefaultAsync(p => p.Slug == slug && p.IsActive);
}
// --- NEUE METHODE ---
public async Task<Product?> GetProductByIdForUpdateAsync(Guid id)
{
return await _context.Products
.Include(p => p.Images)
.Include(p => p.Productcategories)
.FirstOrDefaultAsync(p => p.Id == id);
}
public async Task AddProductAsync(Product product)
{
await _context.Products.AddAsync(product);
await _context.SaveChangesAsync();
}
// --- KORRIGIERTE UPDATE-METHODE (OHNE PARAMETER) ---
public async Task UpdateProductAsync(Product product)
{
// Wir sagen dem DbContext explizit, dass der Zustand dieser Entität "Modifiziert" ist.
// Das zwingt EF Core dazu, ALLE Eigenschaften der Entität in der UPDATE-Anweisung zu berücksichtigen.
// Es umgeht alle möglichen Probleme mit dem Change Tracking, die durch verschiedene Kontexte
// oder komplexe Beziehungs-Updates entstehen können.
_context.Entry(product).State = EntityState.Modified;
await _context.SaveChangesAsync();
}
public async Task DeleteProductAsync(Guid id)
{
var product = await GetProductByIdAsync(id);
if (product != null)
{
_context.Products.Remove(product);
await _context.SaveChangesAsync();
}
}
}
}