public bool AddProject([FromBody] ProjectViewModel viewModel) { using var transaction = _dbContext.Database.BeginTransaction(); try { var project = new Project(viewModel.Name, viewModel.StatusId); var projectEntity = _dbContext.Set <Project>().Add(project); _dbContext.SaveChanges(); var projectId = projectEntity.Entity.Id; var periods = viewModel.Periods; foreach (var period in periods) { var periodId = GetPeriodForViewModel(period).Id; var projectPeriodCapacity = period.Capacity == -1 ? 0 : period.Capacity; var functioningCapacityProject = new FunctioningCapacityProject(projectId, periodId, projectPeriodCapacity); var functioningCapacityResources = new List <FunctioningCapacityResource>(); foreach (var resourceCapacityViewModel in period.Resources) { if (resourceCapacityViewModel.Capacity == -1) { resourceCapacityViewModel.Capacity = 0; } var fres = new FunctioningCapacityResource(projectId, resourceCapacityViewModel.Id, resourceCapacityViewModel.Capacity, periodId); functioningCapacityResources.Add(fres); } if (functioningCapacityResources.Count == 0) { if (functioningCapacityProject.FunctioningCapacity == 0) { continue; } _dbContext.Set <FunctioningCapacityProject>().Add(functioningCapacityProject); } else { _dbContext.Set <FunctioningCapacityResource>().AddRange(functioningCapacityResources); _dbContext.Set <FunctioningCapacityProject>().Add(functioningCapacityProject); } } _dbContext.SaveChanges(); } catch (Exception e) { Console.WriteLine(e); transaction.Rollback(); transaction.Dispose(); return(false); } transaction.Commit(); transaction.Dispose(); return(true); }
private void UpdateOrAddProjectPeriodCapacity(int capacity, int periodId, int projectId) { var periodCapacities = _dbContext.Set <FunctioningCapacityProject>(); var periodCapacity = periodCapacities .FirstOrDefault(functioningCapacityProject => functioningCapacityProject.ProjectId == projectId && functioningCapacityProject.PeriodId == periodId); if (periodCapacity == default) { var newPeriodCapacity = new FunctioningCapacityProject(projectId, periodId, capacity); periodCapacities.Add(newPeriodCapacity); } else { periodCapacity.UpdateFunctioningCapacity(capacity); periodCapacities.Update(periodCapacity); } _dbContext.SaveChanges(); }