private BookingEntity UpdateReports(PutBookingRequest booking) { var year = booking.TimeStamp.Year; var month = booking.TimeStamp.Month; var categoryId = booking.CategoryId; var subCategory = context.Categories.SingleOrDefault(c => c.ParentId == categoryId && EF.Functions.Like(c.Name, $"%{booking.SubCategoryName}%")); CategoryReportEntity subCategoryReport = null; if (subCategory == null) { subCategory = new CategoryEntity() { Name = booking.SubCategoryName, ParentId = booking.CategoryId }; } else { subCategoryReport = context.CategoryReports.Find(subCategory.Id, year, month); } var createSubCategoryReport = subCategoryReport == null; if (createSubCategoryReport) { subCategoryReport = new CategoryReportEntity { Category = subCategory, Year = year, Month = month } } ; subCategoryReport.Spent += (decimal)booking.Amount; if (createSubCategoryReport) { context.CategoryReports.Add(subCategoryReport); } else { context.Update(subCategoryReport); } var categoryReport = context.CategoryReports .Find(categoryId, year, month); var create = categoryReport == null; if (create) { categoryReport = new CategoryReportEntity() { CategoryId = categoryId, Year = year, Month = month }; } categoryReport.Spent += (decimal)booking.Amount; if (create) { context.CategoryReports.Add(categoryReport); } else { context.Update(categoryReport); } var bookingEntity = mapper.Map <BookingEntity>(booking); bookingEntity.CategoryId = subCategory.Id; context.Bookings.Add(bookingEntity); context.SaveChanges(); return(bookingEntity); }