private static Author GetOrCreateAuthor(string authorName, BookStoreEntities context) { if (string.IsNullOrEmpty(authorName)) { return null; } var authorInDB = context.Authors.Where(x => x.FullName.ToLower() == authorName.ToLower()).FirstOrDefault(); if (authorInDB != null) { return authorInDB; } var newAuthor = new Author(); newAuthor.FullName = authorName; return newAuthor; }
private static void AddBook(List<string> authorNames, string title, string isbn, decimal price, string website) { BookStoreEntities context = new BookStoreEntities(); Book newBook = new Book() { Title = title, ISBN = isbn, Price = price, Website = website }; foreach (var authorName in authorNames) { var authorInDB = GetOrCreateAuthor(authorName, context); newBook.Authors.Add(authorInDB); } context.Books.Add(newBook); if (newBook.Authors.Count == 0) { throw new ArgumentException("Author is required"); } context.SaveChanges(); }