HomeLibrary/HomeLibrary.Api/Repositories/BookRepository.cs

72 lines
2.1 KiB
C#

using HomeLibrary.Api.Data;
using HomeLibrary.Api.Entities;
using HomeLibrary.Api.Repositories.Contracts;
using Microsoft.EntityFrameworkCore;
namespace HomeLibrary.Api.Repositories
{
public class BookRepository : IBookRepository
{
private readonly HomeLibraryDbContext homeLibraryDbContext;
public BookRepository(HomeLibraryDbContext homeLibraryDbContext)
{
this.homeLibraryDbContext = homeLibraryDbContext;
}
public Task<Author> GetAuthor(int authorId)
{
throw new NotImplementedException();
}
public async Task<IEnumerable<Author>> GetAuthors()
{
var authors = await this.homeLibraryDbContext.Authors.ToListAsync();
return authors;
}
public Task<Book> GetBook(int bookId)
{
throw new NotImplementedException();
}
public async Task<IEnumerable<Book>> GetBooksByAuthor(int authorId)
{
var books = await (from book in homeLibraryDbContext.Books
where book.AuthorId == authorId
select book).ToListAsync();
return books;
}
public async Task<IEnumerable<Book>> GetBooksByAuthor(string authorName)
{
int authorId = 0;
var authors = await this.homeLibraryDbContext.Authors.ToListAsync();
foreach(var author in authors)
{
if (author.Name == authorName) {
authorId = author.Id;
}
}
if(authorId == 0)
{
return null;
}
else
{
var books = await (from book in homeLibraryDbContext.Books
where book.AuthorId == authorId
select book).ToListAsync();
return books;
}
}
public async Task<IEnumerable<Book>> GetBooks()
{
var books = await this.homeLibraryDbContext.Books.ToListAsync();
return books;
}
}
}