Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static string ImportPosts(InstagraphContext context, string xmlString)
- {
- StringBuilder sb = new StringBuilder();
- // защо не се десериализират с вградения метод за десерилизация:
- //var serializer = new XmlSerializer(typeof(PostDto[]), new XmlRootAttribute("posts"));
- //var deserializedPosts = (PostDto[])serializer.Deserialize(new MemoryStream(Encoding.UTF8.GetBytes(xmlString)));
- var xml = XDocument.Parse(xmlString);
- var deserializedPosts = xml.Root.Elements();
- var validPosts = new List<Post>();
- foreach (var post in deserializedPosts)
- {
- string caption = post.Element("caption")?.Value;
- string user = post.Element("user")?.Value;
- string picture = post.Element("picture")?.Value;
- bool isValid = !String.IsNullOrWhiteSpace(caption) &&
- !String.IsNullOrWhiteSpace(user) &&
- !String.IsNullOrWhiteSpace(picture);
- if (!isValid)
- {
- sb.AppendLine(errorMsg);
- continue;
- }
- bool isUserExists = context.Users.Any(u => u.Username == user);
- bool isPicureExists = context.Pictures.Any(u => u.Path == picture);
- Post currPost = null;
- if (isPicureExists && isUserExists)
- {
- var currUser= context.Users.FirstOrDefault(u => u.Username == user);
- var currPicure = context.Pictures.FirstOrDefault(u => u.Path == picture);
- currPost = new Post()
- {
- Caption = caption,
- User = currUser,
- Picture = currPicure
- };
- validPosts.Add(currPost);
- sb.AppendLine(String.Format(successMsg, $"Post {currPost.Caption}"));
- }
- else
- {
- sb.AppendLine(errorMsg);
- continue;
- }
- }
- context.Posts.AddRange(validPosts);
- context.SaveChanges();
- return sb.ToString().TrimEnd();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement