public ActionResult SelectFriends(string searchTerm) { var loggedUserId = this.User.Identity.GetUserId(); // Take friend relaions where friend's name contains searchTerm var friendRelations = this.Data .FriendRelations .All() .Project() .To<FriendRelationViewModel>() .Where(fr => ((fr.FirstUser.Id == loggedUserId && fr.SecondUser.UserName.ToLower().Contains(searchTerm.ToLower())) || (fr.FirstUser.UserName.ToLower().Contains(searchTerm.ToLower()) && fr.SecondUser.Id == loggedUserId)) && (fr.AreFriends == true)) .ToList(); if (friendRelations.Any()) { // Extract friends users from friend relations var users = new List<UserViewModel>(); foreach (var friendRelation in friendRelations) { users.Add(friendRelation.FirstUser.Id == loggedUserId ? friendRelation.SecondUser : friendRelation.FirstUser); } var chats = new List<ChatViewModel>(); foreach (var user in users) { // Check if two users had already chat, if not create new chat var chat = this.Data.Chats.All().Project().To<ChatViewModel>().FirstOrDefault(ch => (ch.FirstUser.Id == user.Id && ch.SecondUser.Id == loggedUserId) || (ch.FirstUser.Id == loggedUserId && ch.SecondUser.Id == user.Id)); if (chat == null) { var newChat = new Chat() { FirstUserId = loggedUserId, SecondUserId = user.Id, Messages = new List<Message>() }; this.Data.Chats.Add(newChat); this.Data.SaveChanges(); var newChatToView = this.Data.Chats.All() .Project() .To<ChatViewModel>() .FirstOrDefault(ch => ch.FirstUser.Id == loggedUserId && ch.SecondUser.Id == user.Id); chats.Add(newChatToView); } else { chats.Add(chat); } } var returnFriendsMessages = chats .ToDictionary(chat => chat.FirstUser.Id == loggedUserId ? chat.SecondUser : chat.FirstUser, chat => chat.Messages.Any() ? chat.Messages.Last() : null); return PartialView("_DisplayFriendsMessages", returnFriendsMessages); } return new EmptyResult(); }