public static void AddBookComplex(string title, List<string> authors, long? isbn, decimal? price, string webSite, List<ReviewStruct> reviews) { using (BookstoreEntities dbContext = new BookstoreEntities()) { //Create authors List<Author> bookAuthors = new List<Author>(); foreach (var authorName in authors) { Author author = CreateOrLoadAuthor(authorName, dbContext); bookAuthors.Add(author); } //Create reviews List<Review> bookReviews = new List<Review>(); foreach (var reviewInfo in reviews) { Review review = new Review(); if (reviewInfo.AuthorName != null) { review.Author = CreateOrLoadAuthor(reviewInfo.AuthorName, dbContext); } review.Creation_Date = reviewInfo.CreationDate; review.Text = reviewInfo.Text; bookReviews.Add(review); } CheckIsbnUniqueness(isbn, dbContext); //Create book Book newBook = new Book() { Title = title, ISBN = isbn, Price = price, Web_Site = webSite }; foreach (var author in bookAuthors) { newBook.Authors.Add(author); } foreach (var review in bookReviews) { newBook.Reviews.Add(review); } //Save book dbContext.Books.Add(newBook); dbContext.SaveChanges(); } }
public static void AddBook(string title, string authorName, long? isbn, decimal? price) { using (BookstoreEntities dbContext = new BookstoreEntities()) { Author author = CreateOrLoadAuthor(authorName, dbContext); CheckIsbnUniqueness(isbn, dbContext); Book newBook = new Book() { Title = title, ISBN = isbn, Price = price }; newBook.Authors.Add(author); dbContext.Books.Add(newBook); dbContext.SaveChanges(); } }
private static Author CreateOrLoadAuthor(string authorName, BookstoreEntities dbContext) { Author author = dbContext.Authors.FirstOrDefault(a => a.Name == authorName); if (author == null) { author = new Author() { Name = authorName }; } dbContext.SaveChanges(); return author; }