public static void AddBookInDB(string author, string title, string isbn, string price, string site) { Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; BookstoreDBEntities context = new BookstoreDBEntities(); using (context) { Book book = new Book(); if (isbn != null) { book.ISBN = long.Parse(isbn); } else { book.ISBN = null; } if (price != null) { book.Price = decimal.Parse(price); } else { book.Price = null; } book.WebSite = site; book.Title = title.ToLower(); context.Books.Add(book); context.SaveChanges(); // is author in the db var existingAuthor = (from a in context.Authors where a.Name == author.ToLower() select a).FirstOrDefault(); if (existingAuthor == null) { Author newAuthor = new Author() { Name = author.ToLower(), }; context.Authors.Add(newAuthor); context.SaveChanges(); existingAuthor = newAuthor; } book.Authors.Add(existingAuthor); context.SaveChanges(); } }
private static List<Review> AddReviews(BookstoreDBEntities context, List<string[]> reviews) { CultureInfo provider = CultureInfo.InvariantCulture; List<Review> allReviews = new List<Review>(); if (reviews == null) { return null; } foreach (var rev in reviews) { Review review = new Review(); review.Text = rev[0]; if (rev[2] != null) { review.CreationDate = DateTime.ParseExact(rev[2], "d-MMM-yyyy", provider); } else { review.CreationDate = null; } if (rev[1] != null) { string name = rev[1].ToLower(); var existingAuthor = (from a in context.Authors where a.Name == name select a).FirstOrDefault(); //IMPORTANT // I am not very sure is the auther of the review is missing from the database what I must do // so if we must create ne and attach him to the review just uncomment this code or if only // existing authors must be attached do nothing :) // thanks //--------------------------------- if (existingAuthor == null) { Author newAuthor = new Author() { Name = rev[1].ToLower(), }; context.Authors.Add(newAuthor); context.SaveChanges(); existingAuthor = newAuthor; } //---------------------------------- review.Author = existingAuthor; } else { review.Author = null; } allReviews.Add(review); } return allReviews; }
private static List<Author> AddAuthors(BookstoreDBEntities context, List<string[]> authors) { List<Author> authorList = new List<Author>(); if (authorList == null) { return null; } foreach (var author in authors) { string autherName = author[0].ToLower(); var existingAuthor = (from a in context.Authors where a.Name == autherName select a).FirstOrDefault(); if (existingAuthor == null) { Author newAuthor = new Author() { Name = author[0].ToLower(), }; context.Authors.Add(newAuthor); context.SaveChanges(); existingAuthor = newAuthor; } authorList.Add(existingAuthor); } return authorList; }