Esempio n. 1
0
 public void Add <T>(T entity) where T : class
 {
     _logger.LogInformation($"Adding an object of type {entity.GetType()} to the context.");
     _context.Add(entity);
 }
Esempio n. 2
0
        private void SeedCountries()
        {
            using (StreamReader r = new StreamReader("C:/Users/micha/source/Repository/TripWMe/TripWMe/TripWMe.Data/SampleData/countries.json"))
            {
                var settings = new JsonSerializerSettings
                {
                    NullValueHandling     = NullValueHandling.Ignore,
                    MissingMemberHandling = MissingMemberHandling.Ignore
                };

                string json = r.ReadToEnd();
                List <CountriesDataModel> items = JsonConvert.DeserializeObject <List <CountriesDataModel> >(json, settings);
                foreach (var item in items)
                {
                    var continent = new Continent();

                    var existingContinent = _context.Continent.Where(c => c.Name == item.region).FirstOrDefault();

                    if (existingContinent == null)
                    {
                        continent = new Continent()
                        {
                            Name = item.region
                        };
                        _context.Add(continent);
                        _context.SaveChanges();
                    }
                    else
                    {
                        continent = existingContinent;
                    }

                    var region         = new Region();
                    var existingRegion = _context.Region.Where(rg => rg.Name == item.subregion).FirstOrDefault();

                    if (existingRegion == null)
                    {
                        region = new Region()
                        {
                            Name = item.subregion, Continent = continent
                        };
                        _context.Add(region);
                        _context.SaveChanges();
                    }
                    else
                    {
                        region = existingRegion;
                    }

                    var newCountry = new Country()
                    {
                        Name         = item.name.common,
                        OfficialName = item.name.official,
                        Alpha2Code   = item.cca2,
                        Alpha3Code   = item.cca3,
                        Area         = item.area,
                        Region       = region
                    };
                    _context.Add(newCountry);
                    _context.SaveChanges();
                }
            }
        }