public IHttpActionResult Create(GenreModel genre) { if (!this.ModelState.IsValid) { return BadRequest(ModelState); } var newGenre = new Genre { Name = genre.Name }; this.data.Genres.Add(newGenre); this.data.SaveChanges(); genre.GenreId = newGenre.GenreId; return Ok(genre); }
public IHttpActionResult Create(Book book) { if (!this.ModelState.IsValid) { return BadRequest(ModelState); } var newBook = new Book { Title = book.Title, Rewiew = book.Rewiew }; foreach (var genre in book.Genres) { var currGenreFromDb = this.data.Genres.All() .FirstOrDefault(g => g.Name == genre.Name); if (currGenreFromDb == null) { currGenreFromDb = new Genre { Name = genre.Name }; currGenreFromDb.Books.Add(newBook); this.data.Genres.Add(currGenreFromDb); } newBook.Genres.Add(currGenreFromDb); } foreach (var author in book.Authors) { var currentAuthorFromDb = this.data.Authors.All() .FirstOrDefault(a => a.FirstName == author.FirstName && a.LastName == author.LastName); if (currentAuthorFromDb == null) { currentAuthorFromDb = new Author { FirstName = author.FirstName, LastName = author.LastName }; currentAuthorFromDb.Books.Add(newBook); this.data.Authors.Add(currentAuthorFromDb); } newBook.Authors.Add(currentAuthorFromDb); } this.data.Books.Add(newBook); this.data.SaveChanges(); return Ok(newBook.BookId); }