public async Task <Character> CreateAsync(ICreateCharacterModel createModel) { List <Episode> episodes = await _episodeRepository.GetAllByOrDefaultAsync(x => createModel.Episodes.Contains(x.Name)); List <Character> friends = await _characterRepository.GetAllByOrDefaultAsync(x => createModel.Friends.Contains(x.Name)); return(new Character() { Name = createModel.Name, Friends = friends.Select(x => new CharacterFriend() { FriendCharacterId = x.Id }).ToList(), Episodes = episodes.Select(x => new CharacterEpisode() { EpisodeId = x.Id }).ToList() }); }
private async Task SetCharacterFriendsAsync(Character characterToUpdate, List <string> friends) { List <Character> friendsToAssign = await _characterRepository.GetAllByOrDefaultAsync(x => friends.Contains(x.Name)); HashSet <int> friendsToAssignIds = friendsToAssign.Select(x => x.Id).ToHashSet(); List <CharacterFriend>?friendsToRemove = characterToUpdate.Friends.Where(x => !friendsToAssignIds.Contains(x.FriendCharacterId)).ToList(); List <CharacterFriend>?friendsToAdd = friendsToAssignIds.Where(x => !characterToUpdate.Episodes.Any(y => y.EpisodeId == x)) .Select(friendId => new CharacterFriend() { CharacterId = characterToUpdate.Id, FriendCharacterId = friendId }).ToList(); friendsToRemove.ForEach(x => characterToUpdate.Friends.Remove(x)); friendsToAdd.ForEach(x => characterToUpdate.Friends.Add(x)); }