Skip to content

Nikolai L. Børseth #92

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 16 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,21 @@
# C# Entity Framework Intro

1. Fork this repository
2. Clone your fork to your machine
3. Open the ef.intro.sln in Visual Studio

## Completed
Completed everything but super extensions. To run the project, make sure to
update / create an appsettings.json with a connection string. E.g.

<code>
"ConnectionStrings": {
"DefaultConnectionString": "Host=your; Database=values; Username=goes; Password=here;"
}
</code>

Then run migrations and update the database. Test the endpoints in scalar or swagger.
(I recommend scalar)

1. `add-migration init`
1. `update-database init`
1. Start the project
## Setup


Expand Down
7 changes: 7 additions & 0 deletions exercise.webapi/DTO/Author.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace exercise.webapi.DTO
{
public record AuthorPost(string FirstName, string LastName, string Email);
public record AuthorPut(string? FirstName, string? LastName, string? Email);
public record AuthorInternal(int Id, string FirstName, string LastName, string Email);
public record AuthorView(int Id, string FirstName, string LastName, string Email, IEnumerable<BookInternalPublisher> Books);
}
10 changes: 10 additions & 0 deletions exercise.webapi/DTO/Book.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
namespace exercise.webapi.DTO
{
public record BookPost(string Title, int AuthorId, int PublisherId);
public record BookPut(string? Title);
public record BookView(int Id, string Title, IEnumerable<AuthorInternal> Authors, PublisherInternal Publisher, CheckoutInternal? Checkout);
public record BookInternal(int Id, string Title);
public record BookInternalPublisher(int Id, string Title, PublisherInternal Publisher);
public record BookInternalAuthor(int Id, string Title, IEnumerable<AuthorInternal> Authors);
public record BookInternalAuthorPublisher(int Id, string Title, IEnumerable<AuthorInternal> Authors, PublisherInternal Publisher);
}
6 changes: 6 additions & 0 deletions exercise.webapi/DTO/Checkout.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace exercise.webapi.DTO
{
public record CheckoutPost(int BookId);
public record CheckoutView(int Id, DateTime CheckoutTime, DateTime? ReturnTime, DateTime ExpectedReturnTime, BookInternalAuthorPublisher Book);
public record CheckoutInternal(int Id, DateTime CheckoutTime, DateTime? ReturnTime, DateTime ExpectedReturnTime);
}
7 changes: 7 additions & 0 deletions exercise.webapi/DTO/Publisher.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace exercise.webapi.DTO
{
public record PublisherPost(string Name);
public record PublisherPut(string? Name);
public record PublisherView(int Id, string Name, IEnumerable<BookInternalAuthor> Books);
public record PublisherInternal(int Id, string Name);
}
27 changes: 14 additions & 13 deletions exercise.webapi/Data/DataContext.cs
Original file line number Diff line number Diff line change
@@ -1,32 +1,33 @@
using exercise.webapi.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using System.Collections.Generic;
using System.Reflection.Emit;

namespace exercise.webapi.Data
{
public class DataContext : DbContext
public class DataContext(DbContextOptions<DataContext> options) : DbContext(options)
{

public DataContext(DbContextOptions<DataContext> options) : base(options)
{

}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
optionsBuilder.UseInMemoryDatabase("Library");
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Book>().HasMany(x => x.Authors).WithMany(x => x.Books).UsingEntity<AuthorBook>();
modelBuilder.Entity<Book>().HasOne(x => x.Publisher).WithMany(x => x.Books).HasForeignKey(x => x.PublisherId).OnDelete(DeleteBehavior.SetNull);
modelBuilder.Entity<AuthorBook>().HasKey(x => new { x.AuthorId, x.BookId });
modelBuilder.Entity<Checkout>().HasOne(x => x.Book).WithMany(x => x.Checkouts).HasForeignKey(x => x.BookId).OnDelete(DeleteBehavior.SetNull);

Seeder seeder = new Seeder();

modelBuilder.Entity<Author>().HasData(seeder.Authors);
modelBuilder.Entity<Publisher>().HasData(seeder.Publishers);
modelBuilder.Entity<Book>().HasData(seeder.Books);

modelBuilder.Entity<AuthorBook>().HasData(seeder.AuthorBooks);
modelBuilder.Entity<Checkout>().HasData(seeder.Checkouts);
}
public DbSet<Author> Authors { get; set; }
public DbSet<Book> Books { get; set; }
public DbSet<AuthorBook> AuthorBooks { get; set; }
public DbSet<Publisher> Publishers { get; set; }
public DbSet<Checkout> Checkouts { get; set; }

}
}
66 changes: 63 additions & 3 deletions exercise.webapi/Data/Seeder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,13 +79,17 @@ public class Seeder

private List<Author> _authors = new List<Author>();
private List<Book> _books = new List<Book>();
private List<Publisher> _publishers = new List<Publisher>();
private List<AuthorBook> _authorBooks = new List<AuthorBook>();
private List<Checkout> _checkouts = new List<Checkout>();

public Seeder()
{

Random authorRandom = new Random();
Random bookRandom = new Random();

Random publisherRandom = new Random();
Random checkoutRandom = new Random();


for (int x = 1; x < 250; x++)
Expand All @@ -98,20 +102,76 @@ public Seeder()
_authors.Add(author);
}

for (int y = 1; y < 250; y++)
{
Publisher publisher = new Publisher();
publisher.Id = y;
publisher.Name = $"{_lastnames[publisherRandom.Next(_lastnames.Count)]} {_thirdword[bookRandom.Next(_thirdword.Count)]}";
_publishers.Add(publisher);
}


HashSet<Tuple<int, int>> authorBookSet = new HashSet<Tuple<int, int>>();
for (int y = 1; y < 250; y++)
{
Book book = new Book();
book.Id = y;
book.Title = $"{_firstword[bookRandom.Next(_firstword.Count)]} {_secondword[bookRandom.Next(_secondword.Count)]} {_thirdword[bookRandom.Next(_thirdword.Count)]}";
book.AuthorId = _authors[authorRandom.Next(_authors.Count)].Id;
//book.Author = authors[book.AuthorId-1];
book.PublisherId = _publishers[publisherRandom.Next(_publishers.Count)].Id;
AuthorBook authorBook = new AuthorBook();
var ids = new Tuple<int, int>(book.Id, _authors[authorRandom.Next(_authors.Count)].Id);
// Horrible stuff, cant be bothered to do better.
while (authorBookSet.Contains(ids)) ids = new Tuple<int, int>(book.Id, _authors[authorRandom.Next(_authors.Count)].Id);
authorBookSet.Add(ids);
authorBook.BookId = ids.Item1;
authorBook.AuthorId = ids.Item2;
_authorBooks.Add(authorBook);
_books.Add(book);
}

for (int y = 1; y < 250; y++)
{
AuthorBook authorBook = new AuthorBook();
var ids = new Tuple<int, int>(_books[bookRandom.Next(_books.Count)].Id, _authors[authorRandom.Next(_authors.Count)].Id);
if (authorBookSet.Contains(ids)) continue;
authorBookSet.Add(ids);
authorBook.BookId = ids.Item1;
authorBook.AuthorId = ids.Item2;
_authorBooks.Add(authorBook);
}

HashSet<int> checkedOutBooks = new HashSet<int>();
for (int y = 1; y < 100; y++)
{
Checkout checkout = new Checkout();
var bookId = _books[bookRandom.Next(_books.Count)].Id;
if (checkedOutBooks.Contains(bookId)) continue;
bool isReturned = checkoutRandom.NextDouble() < .7;
DateTime checkoutTime = DateTime.UtcNow.AddDays(-checkoutRandom.Next(180));
if (isReturned)
{
bool isOnTime = checkoutRandom.NextDouble() < .65;
if (isOnTime)
{
checkout.ReturnTime = checkoutTime.AddDays(checkoutRandom.Next(14));
} else
{
checkout.ReturnTime = checkoutTime.AddDays(checkoutRandom.Next(15, 60));
}
} else
{
checkedOutBooks.Add(bookId);
}
checkout.Id = y;
checkout.CheckoutTime = checkoutTime;
checkout.BookId = bookId;
_checkouts.Add(checkout);
}
}
public List<Author> Authors { get { return _authors; } }
public List<Book> Books { get { return _books; } }
public List<Publisher> Publishers { get { return _publishers; } }
public List<AuthorBook> AuthorBooks { get { return _authorBooks; } }
public List<Checkout> Checkouts { get { return _checkouts; } }
}
}
164 changes: 164 additions & 0 deletions exercise.webapi/Endpoints/AuthorEndpoints.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
using exercise.webapi.DTO;
using exercise.webapi.Exceptions;
using exercise.webapi.Models;
using exercise.webapi.Repository;

namespace exercise.webapi.Endpoints
{
public static class AuthorEndpoints
{
public static string Path { get; private set; } = "authors";

public static void ConfigureAuthorsEndpoints(this WebApplication app)
{
var group = app.MapGroup(Path);

group.MapPost("/", CreateAuthor);
group.MapGet("/", GetAuthors);
group.MapGet("/{id}", GetAuthor);
group.MapPut("/{id}", UpdateAuthor);
group.MapDelete("/{id}", DeleteAuthor);
}
public static async Task<IResult> CreateAuthor(IRepository<Author> repository, AuthorPost entity)
{
try
{
Author author = await repository.Add(new Author
{
FirstName = entity.FirstName,
LastName = entity.LastName,
Email = entity.Email,
});
return TypedResults.Ok(new AuthorView(
author.Id,
author.FirstName,
author.LastName,
author.Email,
author.Books.Select(b => new BookInternalPublisher(
b.Id,
b.Title,
new PublisherInternal(
b.Publisher.Id,
b.Publisher.Name
)
))
));
}
catch (IdNotFoundException ex)
{
return TypedResults.NotFound(new { ex.Message });
}
catch (Exception ex)
{
return TypedResults.Problem(ex.Message);
}
}
public static async Task<IResult> GetAuthors(IRepository<Author> repository)
{
try
{
IEnumerable<Author> authors = await repository.GetAll();
return TypedResults.Ok(authors.Select(a =>
{
return new AuthorView(
a.Id,
a.FirstName,
a.LastName,
a.Email,
a.Books.Select(b => new BookInternalPublisher(
b.Id,
b.Title,
new PublisherInternal(
b.Publisher.Id,
b.Publisher.Name
)
)));
}));
}
catch (Exception ex)
{
return TypedResults.Problem(ex.Message);
}
}

public static async Task<IResult> GetAuthor(IRepository<Author> repository, int id)
{
try
{
Author author = await repository.Get(id);
return TypedResults.Ok(new AuthorView(
author.Id,
author.FirstName,
author.LastName,
author.Email,
author.Books.Select(b => new BookInternalPublisher(
b.Id,
b.Title,
new PublisherInternal(
b.Publisher.Id,
b.Publisher.Name
)
))
));
}
catch (IdNotFoundException ex)
{
return TypedResults.NotFound(new { ex.Message });
}
catch (Exception ex)
{
return TypedResults.Problem(ex.Message);
}
}
public static async Task<IResult> UpdateAuthor(IRepository<Author> bookRepository, IRepository<Author> authorRepository, int id, AuthorPut entity)
{
try
{
Author author = await bookRepository.Get(id);
if (entity.FirstName != null) author.FirstName = entity.FirstName;
if (entity.LastName != null) author.LastName = entity.LastName;
if (entity.Email != null) author.Email = entity.Email;

author = await bookRepository.Update(author);
return TypedResults.Ok(new AuthorView(
author.Id,
author.FirstName,
author.LastName,
author.Email,
author.Books.Select(b => new BookInternalPublisher(
b.Id,
b.Title,
new PublisherInternal(
b.Publisher.Id,
b.Publisher.Name
)
))
));
}
catch (IdNotFoundException ex)
{
return TypedResults.NotFound(new { ex.Message });
}
catch (Exception ex)
{
return TypedResults.Problem(ex.Message);
}
}
public static async Task<IResult> DeleteAuthor(IRepository<Author> repository, int id)
{
try
{
Author author = await repository.Delete(id);
return TypedResults.Ok(new { Message = $"Deleted Author with FirstName = {author.FirstName}" });
}
catch (IdNotFoundException ex)
{
return TypedResults.NotFound(new { ex.Message });
}
catch (Exception ex)
{
return TypedResults.Problem(ex.Message);
}
}
}
}
20 changes: 0 additions & 20 deletions exercise.webapi/Endpoints/BookApi.cs

This file was deleted.

Loading