Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var deserialized = JsonConvert.DeserializeObject<ImportAuthorDto[]>(jsonString);
- var authors = new List<Author>();
- StringBuilder sb = new StringBuilder();
- foreach (var dto in deserialized )
- {
- var mailExists = context.Authors.FirstOrDefault(m=>m.Email==dto.Email);
- if (!IsValid(dto) || !dto.Books.All(IsValid) || mailExists!=null)
- {
- sb.Append(ErrorMessage);
- continue;
- }
- var books = new List<int>();
- foreach (var bookDto in dto.Books)
- {
- var book = context.Books.FirstOrDefault(b=>b.Id==bookDto.Id);
- if (book==null)
- {
- continue;
- }
- books.Add(bookDto.Id);
- }
- var author = new Author
- {
- FirstName = dto.FirstName,
- LastName = dto.LastName,
- Phone = dto.Phone,
- Email = dto.Email,
- AuthorsBooks = books.Select(b => new AuthorBook
- {
- BookId = b
- }
- ).ToArray()
- };
- authors.Add(author);
- string authorName = $"{author.FirstName} {author.LastName}";
- sb.AppendLine(string.Format(SuccessfullyImportedAuthor,authorName,author.AuthorsBooks.Count));
- }
- context.AddRange(authors);
- context.SaveChanges();
- return sb.ToString();
- }
- -----
- public class ImportAuthorDto
- {
- [MinLength(3), MaxLength(30), Required]
- public string FirstName { get; set; }
- [MinLength(3), MaxLength(30), Required]
- public string LastName { get; set; }
- [EmailAddress]
- [Required]
- public string Email { get; set; }
- [RegularExpression(@"^[0-9]{3}-[0-9]{3}-[0-9]{4}$"), Required]
- public string Phone { get; set; }
- public ICollection<ImportBookDto> Books { get; set; }
- }
- -----
- public class ImportBookDto
- {
- [Required]
- public int Id { get; set; }
- }
Add Comment
Please, Sign In to add comment