private static Author CreateOrLoadAuthor(BookstoreEntities dbContext, string authorName) { Author existingAuthor = dbContext.Authors.Where(a => a.Name == authorName.ToLower()).FirstOrDefault(); if (existingAuthor != null) { return existingAuthor; } else { Author newAuthor = new Author() { Name = authorName.ToLower() }; dbContext.Authors.Add(newAuthor); dbContext.SaveChanges(); return newAuthor; } }
public static void ImportBooksAndAuthors(string bookTitle, string isbn, string author, decimal? price, string webSite) { using (BookstoreEntities dbContext = new BookstoreEntities()) { Book newBook = new Book() { Title = bookTitle.ToLower(), ISBN = isbn, Price = price, website = webSite, }; Author bookAutor = CreateOrLoadAuthor(dbContext, author); newBook.Authors.Add(bookAutor); dbContext.Books.Add(newBook); dbContext.SaveChanges(); } }
public static void ImportBooksAuthorsAndReviews(string bookTitle, string isbn, decimal? price, string webSite, List<string> authorsNames, List<ReviewData> reviewsData) { using (BookstoreEntities dbContext = new BookstoreEntities()) { Book newBook = new Book { Title = bookTitle.ToLower(), ISBN = isbn, Price = price, website = webSite, }; foreach (string authorName in authorsNames) { Author bookAutor = CreateOrLoadAuthor(dbContext, authorName); newBook.Authors.Add(bookAutor); } foreach (ReviewData reviewData in reviewsData) { Review newReview = new Review() { Content = reviewData.Content, CreationDate = reviewData.Date, }; if (reviewData.AuthorName != null) { newReview.Author = CreateOrLoadAuthor(dbContext, reviewData.AuthorName); } newBook.Reviews.Add(newReview); } dbContext.Books.Add(newBook); dbContext.SaveChanges(); } }