public IActionResult AddNewDevice(DeviceDetailsViewModel device) { if (ModelState.IsValid) { //check if manufacturer exists. If not, create it. Manufacturer manufacturer = _manufacturerRepository.GetManufacturerByName(device.ManufacturerName); if (manufacturer == null) { Manufacturer newManufacturer = new Manufacturer() { Name = device.ManufacturerName }; _manufacturerRepository.AddNewManufacturer(newManufacturer); manufacturer = _manufacturerRepository.GetManufacturerByName(device.ManufacturerName); } Models.Type type = _typeRepository.GetTypeByName(device.TypeName); if (type == null) { Models.Type newType = new Models.Type() { Name = device.TypeName }; _typeRepository.AddNewType(newType); type = _typeRepository.GetTypeByName(device.TypeName); } Models.OperatingSystem operatingSystem = _operatingSystemRepository.GetOperatingSystemByName(device.OperatingSystemName); if (operatingSystem == null) { Models.OperatingSystem newOS = new Models.OperatingSystem() { Name = device.OperatingSystemName }; _operatingSystemRepository.AddNewOperatingSystem(newOS); operatingSystem = _operatingSystemRepository.GetOperatingSystemByName(device.OperatingSystemName); } OSversion osVersion = _osVersionRepository.GetOSversionByName(device.OSversionName); if (osVersion == null) { OSversion newOSversion = new OSversion() { Name = device.OSversionName }; _osVersionRepository.AddNewOSversion(newOSversion); osVersion = _osVersionRepository.GetOSversionByName(device.OSversionName); } Processor processor = _processorRepository.GetProcessorByName(device.ProcessorName); if (processor == null) { Processor newProcessor = new Processor() { Name = device.ProcessorName }; _processorRepository.AddNewProcessor(newProcessor); processor = _processorRepository.GetProcessorByName(device.ProcessorName); } RAMamount ramAmount = _ramAmountRepository.GetRAMamountBySize(device.RAMamountSize); if (ramAmount == null) { RAMamount newRAMamount = new RAMamount() { Size = device.RAMamountSize }; _ramAmountRepository.AddNewRAMamount(newRAMamount); ramAmount = _ramAmountRepository.GetRAMamountBySize(device.RAMamountSize); } User user = _userRepository.GetUserByName(device.UserName); Device newDevice = new Device() { Name = device.Name, ManufacturerId = manufacturer.ManufacturerId, Manufacturer = manufacturer, TypeId = type.Id, Type = type, OperatingSystemId = operatingSystem.Id, OperatingSystem = operatingSystem, OSversionId = osVersion.Id, OSversion = osVersion, ProcessorId = processor.Id, Processor = processor, RAMamountId = ramAmount.Id, RAMamount = ramAmount, UserId = user.Id, User = user }; _deviceRepository.AddNewDevice(newDevice); return(RedirectToAction("DeviceAdded")); } else { return(View(device)); } }