lucamilan
8/7/2016 - 7:48 AM

Static class for seeding via EF, uses IServiceScopeFactory

Static class for seeding via EF, uses IServiceScopeFactory

  public static class Seeder
    {
        public static void Seedit(string jsonData, IServiceProvider serviceProvider)
        {
            List<WeatherEvent> events =
            JsonConvert.DeserializeObject<List<WeatherEvent>>(jsonData);
            using (var serviceScope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
            {
                var context = serviceScope.ServiceProvider.GetService<WeatherContext>();
                if (!context.WeatherEvents.Any())
                {
                    context.AddRange(events);
                    context.SaveChanges();
                }
            }
        }

    }