示例#1
0
        public static string ImportSongs(MusicHubDbContext context, string xmlString)
        {
            var sb = new StringBuilder();

            var songsDtos = XmlConverter.Deserializer <ImportSongDto>(xmlString, "Songs");

            var songs = new List <Song>();

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

                DateTime createdOn;
                bool     isCreatedOnValid = DateTime.TryParseExact(song.CreatedOn, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out createdOn);

                if (!isCreatedOnValid)
                {
                    sb.AppendLine(ErrorMessage);
                    continue;
                }

                TimeSpan duration;
                bool     isDurationValid = TimeSpan.TryParseExact(song.Duration, "c", CultureInfo.InvariantCulture, TimeSpanStyles.None, out duration);

                if (!isDurationValid)
                {
                    sb.AppendLine(ErrorMessage);
                    continue;
                }

                var album     = context.Albums.Find(song.AlbumId);
                var writer    = context.Writers.Find(song.WriterId);
                var songTitle = songs.Any(s => s.Name == song.Name);

                if (album == null || writer == null || songTitle)
                {
                    sb.AppendLine(ErrorMessage);
                    continue;
                }

                Genre genre;
                bool  isValidGenre = Enum.TryParse(song.Genre, out genre);
                if (!isValidGenre)
                {
                    sb.AppendLine(ErrorMessage);
                    continue;
                }

                var newSong = new Song
                {
                    Name      = song.Name,
                    Duration  = duration,
                    CreatedOn = createdOn,
                    Genre     = genre,
                    AlbumId   = song.AlbumId,
                    WriterId  = song.WriterId,
                    Price     = song.Price
                };

                songs.Add(newSong);
                sb.AppendLine(string.Format(SuccessfullyImportedSong, newSong.Name, newSong.Genre, newSong.Duration));
            }

            context.Songs.AddRange(songs);
            context.SaveChanges();

            return(sb.ToString().TrimEnd());
        }