public void SavePage(SaveContentPageRequestDto request) { var system = _context.Systems .Include(x => x.Pages) .ThenInclude(x => x.Editions) .Include(x => x.Categories) .First(x => x.ExternalId == request.SystemExternalId); Edition newEdition; var existingPage = system.Pages .FirstOrDefault(x => x.ExternalId == request.ExternalId); if (existingPage == null) { newEdition = new Edition(); newEdition.SetAwardedXp(request.AwardedXp); newEdition.SetEditionDescription(string.Empty); existingPage = new ContentPage(request.Title); existingPage.SetExternalId(request.ExternalId); system.Pages.Add(existingPage); } else { var latestEdition = existingPage.LatestEdition(); newEdition = new Edition(latestEdition.Version); newEdition.SetAwardedXp(latestEdition.CalculatedAwardedXp()); newEdition.SetEditionDescription(request.EditionDescription); newEdition.IncreaseVersion((Edition.VersionUpdate)request.Version); } newEdition.SetContents(request.Contents); existingPage.AddEdition(newEdition); if (request.Categories != null) { foreach (var category in request.Categories) { if (!existingPage.Categories.Any(x => x.Category.Name == category.Name)) { var newCategory = new Category(category.Name); if (category.Badge != null) { var badge = system.Badges .Where(x => x.SystemId == system.Id) .FirstOrDefault(x => x.Name == category.Badge.Name); newCategory.SetBadge(badge); } existingPage.AddCategory(newCategory); } } } _context.SaveChanges(); }