public bool UpdateUserRepositories(string userId, List <GithubRepository> repos) { var user = _context.Users.FirstOrDefault(x => x.UserId == userId); if (user == null) { user = new User { UserId = userId }; _context.Users.Add(user); _context.SaveChanges(); } var existingList = GetUserRepositories(userId); var deleted = existingList?.Except(repos, x => x.FullName)?.ToList() ?? new List <GithubRepository>(); var added = repos?.Except(existingList, x => x.FullName)?.ToList() ?? new List <GithubRepository>(); foreach (var add in added) { var existingRepo = _context.Repositories.FirstOrDefault(x => x.FullName == add.FullName); if (existingRepo != null) { add.Id = existingRepo.Id; } } var reposToAdd = added.Where(x => x.Id == 0).ToList(); if (reposToAdd.Any()) { _context.Repositories.AddRange(reposToAdd); _context.SaveChanges(); } _context.Set <UserRepository>().AddRange(added.Select(x => new UserRepository { User = user, Repository = x })); _context.Set <UserRepository>().RemoveRange(deleted.Select(x => new UserRepository { User = user, Repository = x })); _context.SaveChanges(); return(true); }
public Task SetAsync(string key, IResponse value) { using (var context = new GithubCacheContext(_config)) { var item = context.Requests.FirstOrDefault(x => x.Key == key); if (item != null) { item.Request = JsonConvert.SerializeObject(value); return(Task.FromResult(context.SaveChanges())); } context.Requests.Add(new GithubRequest { Key = key, Request = JsonConvert.SerializeObject(value) }); //Note: This should not be `context.SaveChangeAsync` as the context is disposed by the time this // would execute. So instead, we save it synchronously and wrap it in a task for the return value. return(Task.FromResult(context.SaveChanges())); } }