private Task <bool> Edit(WeatherOfTheDay weatherOfTheDay, AddOrEditWeatherOfTheDayCommand request, CancellationToken cancellationToken) { using (var scope = new TransactionScope()) { if (weatherOfTheDay.WeatherTemperatures.Count != 24) { throw new Exception("Weather record doesn't have 24 temperature measurements"); } weatherOfTheDay.DateUtc = request.SelectedDate; weatherOfTheDay.CityId = request.SelectedCityId; weatherOfTheDay.Cloudiness = request.Cloudiness; weatherOfTheDay.Humidity = request.Humidity; weatherOfTheDay.Pressure = request.Pressure; weatherOfTheDay.RainChance = request.RainChance; weatherOfTheDay.WindSpeed = request.WindSpeed; _db.SaveChanges(); foreach (var weatherTemperatureOfTheDay in weatherOfTheDay.WeatherTemperatures) { //null reference possible but If at this point it shows up then the exception should be thrown weatherTemperatureOfTheDay.TemperatureC = request .Temperatures .SingleOrDefault(x => x.Time.TimeOfDay == weatherTemperatureOfTheDay.DayTimeUtc.TimeOfDay) .Temperature; } _db.SaveChanges(); scope.Complete(); } return(Task.Run(() => true, cancellationToken)); }
private Task <bool> Add(AddOrEditWeatherOfTheDayCommand request, CancellationToken cancellationToken) { using (var scope = new TransactionScope()) { var weatherModel = new WeatherOfTheDay { DateUtc = request.SelectedDate, CityId = request.SelectedCityId, Cloudiness = request.Cloudiness, Humidity = request.Humidity, Pressure = request.Pressure, RainChance = request.RainChance, WindSpeed = request.WindSpeed, CreatedDateUtc = DateTime.Now, }; _db.Weather.Add(weatherModel); if (_db.SaveChanges() <= 0) { return(Task.Run(() => false, cancellationToken)); } var temperaturesModel = new List <WeatherTemperatureOfTheDay>(request.Temperatures.Select(x => new WeatherTemperatureOfTheDay { DayTimeUtc = x.Time, TemperatureC = x.Temperature, WeatherOfTheDayId = weatherModel.Id }).ToList()); _db.AddRange(temperaturesModel); if (_db.SaveChanges() != 24) { throw new Exception("Didn't add all 24 temperature measurements"); } scope.Complete(); return(Task.Run(() => true, cancellationToken)); } }