I'm working on asp.net core 7 MVC project, and want to seed list of countries with cities to Database from locally stored json file (more than 600000 lines)
Here is a sample of JSON file
[{
"id": 1,
"name": "Afghanistan",
"iso3": "AFG",
"iso2": "AF",
"cities": [
{
"id": 141,
"name": "‘Alāqahdārī Dīshū"
},
{
"id": 53,
"name": "Aībak"
},
{
"id": 50,
"name": "Andkhoy"
},
{
"id": 136,
"name": "Āqchah"
},
{
"id": 137,
"name": "Ārt Khwājah"
},
{
"id": 51,
"name": "Asadabad"
},
{
"id": 52,
"name": "Ashkāsham"
},
{
"id": 138,
"name": "Āsmār"
},
{
"id": 54,
"name": "Baghlān"
},
{
"id": 55,
"name": "Balkh"
},
]
}
]
This is what I tried to do.
Country Model:
public class Country
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
public string Name { get; set; }
public string ISO2 { get; set; }
public string ISO3 { get; set; }
public ICollection<City> Cities { get; set; }
}
City Model
public class City
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
public string Name { get; set; }
public int CountryId { get; set; }
public Country Country { get; set; }
}
Code for deserializing
public static async Task SeedCountries(AppDbContext context, IWebHostEnvironment web)
{
if (!(context.Countries.Count() > 0) || !(context.Cities.Count() > 0))
{
string json = await System.IO.File.ReadAllTextAsync(Path.Combine(web.ContentRootPath, "countries.json"));
var jsonObject = JArray.Parse(json);
IList<Country> countries = new List<Country>();
foreach (var item in jsonObject)
{
Country country = item.ToObject<Country>();
var citites = item["cities"] as JArray;
var citis = new City();
countries.Add(country);
foreach (var city in citites)
{
City cities = city.ToObject<City>();
cities.CountryId = country.Id;
context.Cities.Add(cities);
context.Entry(cities).State = Microsoft.EntityFrameworkCore.EntityState.Detached;
}
}
await context.Countries.AddRangeAsync(countries);
await context.SaveChangesAsync();
}
}
The problem with that is performance as its shown in this image: