private static void Main() { // pres Enable-Migrations // Database.SetInitializer(new MigrateDatabaseToLatestVersion<StudentSystemDbContext, Configuration>()); //db.Database.Initialize(true); var context = new MountainsContext(); var bulgaria = new Country { Code = "1S", Name = "Bulagria" }; var rila = new Mountain { Name = "Rila", Countries = { bulgaria } }; var musala = new Peak { Name = "Musala", Mountain = rila, Elevation = 2925 }; context.Countries.Add(bulgaria); context.Mountains.Add(rila); context.Peaks.Add(musala); context.SaveChanges(); var countriesQuery = context.Countries.Select(c => new { ContryName = c.Name, Mountains = c.Mountains.Select(m => new { m.Name, m.Peaks }) }); foreach (var country in countriesQuery) { Console.WriteLine("Country: " + country.ContryName); foreach (var mountain in country.Mountains) { Console.WriteLine(" Mountain: " + mountain.Name); foreach (var peak in mountain.Peaks) { Console.WriteLine("\t{0} ({1})", peak.Name, peak.Elevation); } } } }
private static void AddCountryToDb(MountainsContext context, MountainDTO mountainDTO) { if(mountainDTO.MountainName == null) { throw new Exception("Mountain name is required"); } var m = new Mountain() { Name = mountainDTO.MountainName }; foreach (var peak in mountainDTO.Peaks) { if(peak.PeakName == null) { throw new Exception("Peak name is required"); } if(peak.Elevation == null) { throw new Exception("Peak elevation is required"); } var peakToDb = new Peak() { Name = peak.PeakName, Elevation = peak.Elevation.GetValueOrDefault() }; m.Peaks.Add(peakToDb); } foreach (var countryName in mountainDTO.Countries) { var country = context.Countries.FirstOrDefault(c => c.Name == countryName); if (country == null) { country = new Country() { Code = countryName.ToUpper().Substring(0, 2), Name = countryName }; } country.Mountains.Add(m); context.Countries.Add(country); } context.Mountains.Add(m); }