public static void AddBook(XmlNodeList authors, XmlNodeList reviews, string title, string webSite, decimal price, string isbn) { if (title == null) { throw new ArgumentNullException("BookTitle must not be null"); } BookStoreDB context = new BookStoreDB(); Book newBook = new Book(); foreach (XmlNode author in authors) { string authorName = author.InnerText; newBook.Authors.Add(CreateOrLoadAuthor(context, authorName)); } foreach (XmlNode review in reviews) { string authorName = null; XmlAttributeCollection atributes = review.Attributes; string reviewText = review.InnerText.Trim(); if (review.Attributes.GetNamedItem("author") != null) { authorName = review.Attributes.GetNamedItem("author").Value; } string date = ""; if (review.Attributes.GetNamedItem("date") != null) { date = review.Attributes["date"].Value; } DateTime parsed; string dateFormat = "d-MMM-yyyy"; DateTime.TryParseExact(date, dateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsed); newBook.Reviews.Add(CreateReview(context, parsed, authorName, reviewText)); } newBook.Title = title; newBook.Website = webSite; newBook.Price = price; newBook.Isbn = isbn; context.Books.Add(newBook); context.SaveChanges(); }
// Task 1 - 2 are in Code First aproach and I em using DataAnotattions Atributes for adding constraints public static void AddBook(string author, string title, string webSite, decimal price, string isbn) { if (author == null || title == null) { throw new ArgumentNullException("BookTitle and BookAuthor(s) must not be null"); } BookStoreDB context = new BookStoreDB(); Book newBook = new Book(); newBook.Authors.Add(CreateOrLoadAuthor(context, author)); newBook.Title = title; newBook.Website = webSite; newBook.Price = price; newBook.Isbn = isbn; context.Books.Add(newBook); context.SaveChanges(); }
private static Author CreateOrLoadAuthor( BookStoreDB context, string authorName) { Author existingAuthor = (from u in context.Authors where u.Name == authorName select u).FirstOrDefault(); if (existingAuthor != null) { return existingAuthor; } Author newAuthor = new Author(); newAuthor.Name = authorName; context.Authors.Add(newAuthor); context.SaveChanges(); return newAuthor; }