public Box CreateBox(Box box) { DateTime currentDateTime = DateTime.Now; box.DateCreated = currentDateTime; box.DateModified = currentDateTime; _context.Add(box); _context.SaveChanges(); int boxId = box.Id; List <DHT> dhts = _context.DHTs.Where(d => d.DeviceId == box.DHTId).ToList(); List <MotionSensor> motionSensors = _context.MotionSensors.Where(d => d.DeviceId == box.MotionSensorId).ToList(); foreach (DHT dht in dhts) { dht.BoxId = boxId; dht.DateCreated = currentDateTime; dht.DateModified = currentDateTime; _context.Update(dht); _context.SaveChanges(); } foreach (MotionSensor motionSensor in motionSensors) { motionSensor.BoxId = boxId; motionSensor.DateCreated = currentDateTime; motionSensor.DateModified = currentDateTime; _context.Update(motionSensor); _context.SaveChanges(); } _context.SaveChanges(); return(box); }