private static void ImportSuppliers() { var context = new CarDealerDbContext(); var mapperConfig = new MapperConfiguration(cfg => { cfg.AddProfile <CarDealerProfile>(); }); var mapper = mapperConfig.CreateMapper(); var xmlString = File.ReadAllText("ImportXmls/suppliers.xml"); var serializer = new XmlSerializer(typeof(SupplierDto[]), new XmlRootAttribute("suppliers")); var deserializeSuppliers = (SupplierDto[])serializer.Deserialize( new StringReader(xmlString)); var suppliers = new List <Supplier>(); foreach (var deserializeSupplier in deserializeSuppliers) { if (!IsValid(deserializeSupplier)) { continue; } var supplier = mapper.Map <Supplier>(deserializeSupplier); suppliers.Add(supplier); } context.AddRange(suppliers); context.SaveChanges(); }
private static void SeedManufacturersWithModels(CarDealerDbContext dbContext) { if (!dbContext.Manufacturers.Any()) { var manufacturers = File.ReadAllText(WebConstants.ManufacturersPath); var deserializedManufacturersWithModels = JsonConvert.DeserializeObject <ManufacturerDto[]>(manufacturers); var allManufacturers = new List <Manufacturer>(); foreach (var manufacturerDto in deserializedManufacturersWithModels) { var manufacturer = new Manufacturer { Name = manufacturerDto.Name, Models = manufacturerDto .Models .Select(modelName => new Model { Name = modelName }) .ToList() }; allManufacturers.Add(manufacturer); } dbContext.AddRange(allManufacturers); dbContext.SaveChanges(); } }
private static void ImportParts() { var context = new CarDealerDbContext(); var mapperConfig = new MapperConfiguration(cfg => { cfg.AddProfile <CarDealerProfile>(); }); var mapper = mapperConfig.CreateMapper(); var xmlString = File.ReadAllText("ImportXmls/parts.xml"); var serializer = new XmlSerializer(typeof(PartDto[]), new XmlRootAttribute("parts")); var deserializeParts = (PartDto[])serializer.Deserialize(new StringReader(xmlString)); var parts = new List <Part>(); foreach (var deserializePart in deserializeParts) { if (!IsValid(deserializePart)) { continue; } //take random supplier var suppliers = context.Suppliers.ToList(); var supplierId = new Random().Next(suppliers.Count - 1); var supplier = suppliers.FirstOrDefault(id => id.Id == supplierId); suppliers.Remove(supplier); var partDto = new PartDto() { Name = deserializePart.Name, Price = deserializePart.Price, Quantity = deserializePart.Quantity, SupplierId = supplierId }; var part = mapper.Map <Part>(partDto); parts.Add(part); } context.AddRange(parts); context.SaveChanges(); }