Example #1
0
        static void Main()
        {
            // Working!
            var db = new CarsDbContext();
            db.Configuration.AutoDetectChangesEnabled = false;

            for (int i = 0; i <= 4; i++)
            {
                var filePath = "../../../../JSONData/data." + i + ".json";
                var jsonText = File.ReadAllText(filePath);

                JArray allCars = JArray.Parse(jsonText);

                Console.WriteLine("Adding cars from file: {0}", filePath);
                int counter = 0;
                foreach (var car in allCars)
                {
                    Manufacturer newManufacturer = new Manufacturer
                    {
                        Name = car["ManufacturerName"].ToString()
                    };


                    Dealer newDealer = new Dealer
                    {
                        Name = car["Dealer"]["Name"].ToString()
                    };
                    newDealer.Cities.Add(new City { Name = car["Dealer"]["City"].ToString() });

                    Car newCar = new Car
                    {
                        Model = car["Model"].ToString(),
                        TransmisionType = int.Parse(car["TransmissionType"].ToString()),
                        Price = decimal.Parse(car["Price"].ToString()),
                        Year = int.Parse(car["Year"].ToString()),
                        Manufacturer = newManufacturer,
                        Dealer = newDealer
                    };

                    newManufacturer.Cars.Add(newCar);
                    newDealer.Cars.Add(newCar);

                    db.Manufacturers.Add(newManufacturer);
                    db.Dealers.Add(newDealer);
                    db.Cars.Add(newCar);
                    Console.Write(".");

                    if (counter % 100 == 0)
                    {
                        db.SaveChanges();
                    }

                    counter++;
                }
                db.SaveChanges();
                Console.WriteLine("\nFile Read Complete -> All Cars where added successfuly!");
                Console.WriteLine("\n");
            }
            db.Configuration.AutoDetectChangesEnabled = false;
        }
        private static void ImportData()
        {
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<CarsDbContext, Configuration>());

            var cars = new List<Car>();

            var files = Directory.GetFiles(Environment.CurrentDirectory).Where(fileName => fileName.EndsWith(".json")).ToList();

            foreach (var file in files)
            {
                var fileContent = File.ReadAllText(file);
                var fileCars = JsonConvert.DeserializeObject<IEnumerable<Car>>(fileContent);
                cars.AddRange(fileCars);
                Console.WriteLine("{0} read.", file);
            }

            var manufacturerNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
            var cityNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
            var dealerNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

            foreach (var car in cars)
            {
                manufacturerNames.Add(car.ManufacturerName);
                cityNames.Add(car.Dealer.City);
                dealerNames.Add(car.Dealer.Name);
            }

            var db = new CarsDbContext();
            db.Configuration.AutoDetectChangesEnabled = false;

            // Add cities
            Console.WriteLine("Adding cities...");
            foreach (var cityName in cityNames)
            {
                db.Cities.AddOrUpdate(c => c.Name, new City { Name = cityName });
            }

            db.SaveChanges();
            Console.WriteLine("Cities added.");

            // Add manufacturers
            Console.WriteLine("Adding manufacturers...");
            foreach (var manufacturerName in manufacturerNames)
            {
                db.Manufacturers.AddOrUpdate(m => m.Name, new Manufacturer { Name = manufacturerName });
            }

            db.SaveChanges();
            Console.WriteLine("Manufacturers added.");

            // Add dealers
            Console.WriteLine("Adding dealers...");
            foreach (var dealerName in dealerNames)
            {
                db.Dealers.AddOrUpdate(d => d.Name, new Dealer { Name = dealerName });
            }

            db.SaveChanges();
            Console.WriteLine("Dealers added.");

            // Add cars
            Console.Write("Adding cars");
            for (int carIndex = 0; carIndex < cars.Count; carIndex++)
            {
                var car = cars[carIndex];
                var databaseCarCity = db.Cities.FirstOrDefault(x => x.Name == car.Dealer.City);
                if (databaseCarCity == null)
                {
                    throw new ArgumentException("Invalid city name!");
                }

                var databaseCar = new Cars.Models.Car
                                      {
                                          Dealer = db.Dealers.FirstOrDefault(d => d.Name == car.Dealer.Name),
                                          Manufacturer =
                                              db.Manufacturers.FirstOrDefault(x => x.Name == car.ManufacturerName),
                                          Model = car.Model,
                                          Price = car.Price,
                                          TransmissionType = car.TransmissionType,
                                          Year = (short)car.Year,
                                      };

                db.Configuration.AutoDetectChangesEnabled = true;
                if (!databaseCar.Dealer.Cities.Any(c => c.Name == databaseCarCity.Name))
                {
                    databaseCarCity.Dealers.Add(databaseCar.Dealer);
                }

                db.Cars.Add(databaseCar);

                if (carIndex % 100 == 0)
                {
                    db.SaveChanges();
                    Console.Write(".");
                }

                db.Configuration.AutoDetectChangesEnabled = false;
            }

            Console.WriteLine();

            db.SaveChanges();
            Console.WriteLine("Cars added.");
        }
Example #3
0
        public static void Import()
        {
            var carsToAdd = Directory
                          .GetFiles(Directory.GetCurrentDirectory() + "/JsonFiles/")
                          .Where(f => f.EndsWith("json"))
                          .Select(f => File.ReadAllText(f))
                          .SelectMany(str => JsonConvert.DeserializeObject<IEnumerable<JsonCar>>(str))
                          .ToList();

            var addedCities = new HashSet<string>();
            var addedManufacturers = new HashSet<string>();

            var addedCars = 0;
            var db = new CarsDbContext();
            db.Configuration.AutoDetectChangesEnabled = false;
            Console.WriteLine("Adding cars");
            foreach (var car in carsToAdd)
            {
                var cityName = car.Dealer.City;
                if (!addedCities.Contains(car.Dealer.City))
                {
                    var city = new City
                    {
                        Name = cityName
                    };

                    db.Cities.Add(city);
                    db.SaveChanges();
                    addedCities.Add(cityName);
                }

                var manufacturer = car.ManufacturerName;

                if (!addedManufacturers.Contains(car.ManufacturerName))
                {
                    var newManufacturer = new Manufacturer
                    {
                        Name = manufacturer
                    };
                    addedManufacturers.Add(manufacturer);
                    db.Manufacturers.Add(newManufacturer);
                    db.SaveChanges();
                }

                var dealerToAdd = new Cars.Models.Dealer
                {
                    Name = car.Dealer.Name
                };

                var dbCity = db.Cities
                    .FirstOrDefault(c => c.Name == cityName);
                dealerToAdd.Cities.Add(dbCity);

                var dbManufacturer = db.Manufacturers
                    .FirstOrDefault(m => m.Name == car.ManufacturerName);

                var carToAdd = new Car
                {
                    Manufacturer = dbManufacturer,
                    Dealer = dealerToAdd,
                    Model = car.Model,
                    Price = car.Price,
                    TransmissionType = car.TransmissionType,
                    Year = (short)car.Year
                };

                db.Cars.Add(carToAdd);
                if (addedCars % 100 == 0)
                {
                    Console.Write(".");
                    db.SaveChanges();
                    db.Dispose();
                    db = new CarsDbContext();
                    db.Configuration.AutoDetectChangesEnabled = false;
                }

                addedCars++;
            }

            db.SaveChanges();
            db.Configuration.AutoDetectChangesEnabled = true;
        }