70 lines
1.8 KiB
C#
70 lines
1.8 KiB
C#
using Microsoft.EntityFrameworkCore;
|
|
|
|
namespace Aufgabe14;
|
|
|
|
public class CustomerRepository
|
|
{
|
|
private readonly DbContext _dbContext;
|
|
private readonly DbSet<Customer> _customerSet;
|
|
|
|
public CustomerRepository(DbContext dbContext)
|
|
{
|
|
_dbContext = dbContext;
|
|
_customerSet = _dbContext.Set<Customer>();
|
|
}
|
|
|
|
public List<Customer> GetAll()
|
|
{
|
|
Console.WriteLine("Hier ist die Kundenliste!");
|
|
return _customerSet.ToList();
|
|
}
|
|
|
|
public Customer Get(int id)
|
|
{
|
|
if (_customerSet.Any(c => c.Id == id))
|
|
{
|
|
Console.WriteLine("Hier ist der gewünschte Kunde!");
|
|
return _customerSet.Single(customer => customer.Id == id);
|
|
}
|
|
else
|
|
{
|
|
Console.WriteLine("Den gewünschten Kunden gibt es nicht!");
|
|
return null;
|
|
}
|
|
|
|
}
|
|
|
|
public Customer SaveOrUpdate(Customer customer)
|
|
{
|
|
if (_customerSet.Any(c => c.Id == customer.Id))
|
|
{
|
|
Customer dbCustomer = _customerSet.Single(c => c.Id == customer.Id);
|
|
_customerSet.Update(customer);
|
|
Console.WriteLine("Bestehender Kunde aktualisiert!");
|
|
}
|
|
else
|
|
{
|
|
_customerSet.Add(customer);
|
|
Console.WriteLine("Neuer Kunde angelegt!");
|
|
}
|
|
_dbContext.SaveChanges();
|
|
return customer;
|
|
}
|
|
|
|
public bool Delete(Customer customer)
|
|
{
|
|
if (customer != null)
|
|
{
|
|
if (_customerSet.Any(c => c.Id == customer.Id))
|
|
{
|
|
_customerSet.Remove(customer);
|
|
_dbContext.SaveChanges();
|
|
Console.WriteLine("Kunde gelöscht!");
|
|
return true;
|
|
}
|
|
}
|
|
|
|
Console.WriteLine("Den zu löschenden Kunden gibt es nicht!");
|
|
return false;
|
|
}
|
|
} |