GameLibrary/Repositories/GameRepository.cs

58 lines
1.5 KiB
C#

using GameLibrary.Data;
using GameLibrary.Models;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace GameLibrary.Repositories
{
public class GameRepository : IGameRepository
{
private readonly GameContext _context;
public GameRepository(GameContext context)
{
_context = context;
}
public async Task<IEnumerable<Game>> GetAllGames(string genre = null)
{
if (string.IsNullOrEmpty(genre))
{
return await _context.Games.ToListAsync();
}
return await _context.Games
.Where(g => g.Genres.Contains(genre))
.ToListAsync();
}
public async Task<Game> GetGameById(int id)
{
return await _context.Games.FindAsync(id);
}
public async Task CreateGame(Game game)
{
_context.Games.Add(game);
await _context.SaveChangesAsync();
}
public async Task UpdateGame(Game game)
{
_context.Entry(game).State = EntityState.Modified;
await _context.SaveChangesAsync();
}
public async Task DeleteGame(int id)
{
var game = await _context.Games.FindAsync(id);
if (game != null)
{
_context.Games.Remove(game);
await _context.SaveChangesAsync();
}
}
}
}