Files
NoteApp/noteApi/Repository/NoteRepository.cs
2025-02-08 14:01:15 +01:00

68 lines
1.7 KiB
C#

using Microsoft.EntityFrameworkCore;
using noteApi.Data;
using noteApi.Dtos.Note;
using noteApi.Interfaces;
using noteApi.Mappers;
using noteApi.Models;
namespace noteApi.Repository
{
public class NoteRepository : INoteRepository
{
private readonly ApplicationDbContext _context;
public NoteRepository(ApplicationDbContext context)
{
_context = context;
}
public async Task<Note> CreateAsync(CreateNoteDto noteModel)
{
var note = noteModel.ToNoteFromCreateDto();
await _context.Notes.AddAsync(note);
await _context.SaveChangesAsync();
return note;
}
public async Task<Note?> DeleteAsync(int id)
{
var noteModel = await _context.Notes.FirstOrDefaultAsync(x => x.Id == id);
if (noteModel == null)
{
return null;
}
_context.Notes.Remove(noteModel);
_context.SaveChanges();
return noteModel;
}
public async Task<List<Note>> GetAllAsync()
{
return await _context.Notes.ToListAsync();
}
public async Task<Note?> GetByIdAsync(int id)
{
return await _context.Notes.FindAsync(id);
}
public async Task<Note?> UpdateAsync(int id, CreateNoteDto noteModel)
{
var existingNote = await _context.Notes.FirstOrDefaultAsync(x => x.Id == id);
if (existingNote == null)
{
return null;
}
existingNote.Title = noteModel.Title;
existingNote.Content = noteModel.Content;
_context.SaveChanges();
return existingNote;
}
}
}