/// <summary> /// Accept a specific friend request /// </summary> /// <param name="id">The specific friend Id</param> public async Task <User> AcceptAddFriendRequestAsync(string requestId) { var request = await RemoveFriendRequestByIdAsync(requestId); var user = request?.ToUserId == CurrentUser.Id ? request.FromUser:null; if (user == null) { return(null); } var chat = new Chat() { CreatedByUser = CurrentUser, ChatType = ChatType.Personal }; var uc = new List <UsersChats>() { new UsersChats { Chat = chat, User = CurrentUser, Rools = UserChatRools.Admin }, new UsersChats { Chat = chat, User = user, Rools = UserChatRools.Admin } }; chat.UsersChats = uc; (await Chats.AddAsync(chat)).State = EntityState.Added; await UsersChats.AddRangeAsync(uc); var friends = new Friends() { FromUser = user, ToUser = CurrentUser, Chat = chat }; (await Friends.AddAsync(friends)).State = EntityState.Added; await Db.SaveChangesAsync(); return(user); }
private async Task <Chat> CreateChatAsync(ChatType type, User[] withUsers = null, Chat chat = null) { if (withUsers?.Length == 1 && type == ChatType.Personal) { var existChat = await GetChatWithAsync(withUsers.First().Id); if (existChat != null) { return(existChat); } } chat = new Chat() { Name = chat?.Name, CreatedByUser = CurrentUser, ChatType = chat?.ChatType ?? type }; bool isCurrentUserAdded = false; if (withUsers != null) { foreach (var user in withUsers) { if (withUsers.Length == 1) { chat.UsersChats.Add(new UsersChats() { Chat = chat, User = user, Rools = UserChatRools.Admin }); break; } isCurrentUserAdded = (user.Id == CurrentUser.Id); if (isCurrentUserAdded) { chat.UsersChats.Add(new UsersChats() { Chat = chat, User = user, Rools = UserChatRools.Admin }); } chat.UsersChats.Add(new UsersChats() { Chat = chat, User = user, Rools = UserChatRools.User }); } } if (!isCurrentUserAdded) { chat.UsersChats.Add(new UsersChats() { Chat = chat, User = CurrentUser, Rools = UserChatRools.Admin }); } var entityEntryChat = await Chats.AddAsync(chat); entityEntryChat.State = EntityState.Added; UsersChats.AddRange(chat.UsersChats); //if the problem not solved must separate the UsersChats collection and add it later after saveChages for adding the chat // be cause the UsersChats elements has a references to the chat await Db.SaveChangesAsync(); return(entityEntryChat.Entity); }