apexretrace1

Untitled

Dec 6th, 2019
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.31 KB | None | 0 0
  1.  var deserialized = JsonConvert.DeserializeObject<ImportAuthorDto[]>(jsonString);
  2.  
  3.             var authors = new List<Author>();
  4.  
  5.             StringBuilder sb = new StringBuilder();
  6.  
  7.  
  8.  
  9.             foreach (var dto in deserialized )
  10.             {
  11.                 var mailExists = context.Authors.FirstOrDefault(m=>m.Email==dto.Email);
  12.  
  13.                 if (!IsValid(dto) || !dto.Books.All(IsValid) || mailExists!=null)
  14.                 {
  15.                     sb.Append(ErrorMessage);
  16.                     continue;
  17.                 }
  18.                 var books = new List<int>();
  19.  
  20.                 foreach (var bookDto in dto.Books)
  21.                 {
  22.                     var book = context.Books.FirstOrDefault(b=>b.Id==bookDto.Id);
  23.                     if (book==null)
  24.                     {
  25.                         continue;
  26.                     }
  27.  
  28.                     books.Add(bookDto.Id);
  29.                 }
  30.  
  31.                 var author = new Author
  32.                 {
  33.                     FirstName = dto.FirstName,
  34.                     LastName = dto.LastName,
  35.                     Phone = dto.Phone,
  36.                     Email = dto.Email,
  37.                     AuthorsBooks = books.Select(b => new AuthorBook
  38.                     {
  39.                         BookId = b
  40.                     }
  41.                         ).ToArray()
  42.  
  43.                 };
  44.                 authors.Add(author);
  45.                 string authorName = $"{author.FirstName} {author.LastName}";
  46.                 sb.AppendLine(string.Format(SuccessfullyImportedAuthor,authorName,author.AuthorsBooks.Count));
  47.  
  48.             }
  49.  
  50.             context.AddRange(authors);
  51.             context.SaveChanges();
  52.  
  53.             return sb.ToString();
  54.         }
  55.  
  56. -----
  57.  public class ImportAuthorDto
  58.     {
  59.         [MinLength(3), MaxLength(30), Required]
  60.         public string FirstName { get; set; }
  61.  
  62.         [MinLength(3), MaxLength(30), Required]
  63.         public string LastName { get; set; }
  64.  
  65.         [EmailAddress]
  66.         [Required]
  67.         public string Email { get; set; }
  68.  
  69.         [RegularExpression(@"^[0-9]{3}-[0-9]{3}-[0-9]{4}$"), Required]
  70.         public string Phone { get; set; }
  71.  
  72.         public ICollection<ImportBookDto> Books { get; set; }
  73.     }
  74. -----
  75.  public class ImportBookDto
  76.     {
  77.         [Required]
  78.         public int Id { get; set; }
  79.     }
Add Comment
Please, Sign In to add comment