public static string ImportBooks(BookShopContext context, string xmlString)
        {
            var sb = new StringBuilder();

            var books = new List <Book>();

            var booksDto = XmlConverter.Deserializer <BookImportModel>(xmlString, "Books");

            foreach (var bookDto in booksDto)
            {
                if (!IsValid(bookDto))
                {
                    sb.AppendLine(ErrorMessage);
                    continue;
                }

                var date = DateTime.ParseExact(bookDto.PublishedOn, "MM/dd/yyyy", CultureInfo.InvariantCulture);

                var book = new Book
                {
                    Name        = bookDto.Name,
                    Genre       = (Genre)bookDto.Genre, // possible error on judge
                    Price       = bookDto.Price,
                    Pages       = bookDto.Pages,
                    PublishedOn = date
                };

                books.Add(book);


                sb.AppendLine(String.Format(SuccessfullyImportedBook, book.Name, book.Price));
            }

            context.Books.AddRange(books);
            context.SaveChanges();

            return(sb.ToString().TrimEnd());
        }
Ejemplo n.º 2
0
        public static string ImportBooks(BookShopContext context, string xmlString)
        {
            var root = "Books";
            var data = XmlConverter.Deserializer <ImportBookDTO>(xmlString, root);

            List <Book>   books = new List <Book>();
            StringBuilder sb    = new StringBuilder();

            foreach (var item in data)
            {
                if (IsValid(item))
                {
                    Enum.TryParse(item.Genre.ToString(), true, out Genre genre);
                    var book = new Book
                    {
                        Name        = item.Name,
                        Genre       = genre,
                        Price       = item.Price,
                        Pages       = item.Pages,
                        PublishedOn = DateTime.ParseExact(item.PublishedOn, "MM/dd/yyyy", CultureInfo.InvariantCulture)
                    };

                    books.Add(book);
                    sb.AppendLine(string.Format(SuccessfullyImportedBook, book.Name, book.Price));
                }
                else
                {
                    sb.AppendLine(ErrorMessage);
                }
            }

            context.Books.AddRange(books);
            context.SaveChanges();

            return(sb.ToString());
        }