static void InitializeDb(IServiceProvider services) { var db = services.GetRequiredService <IAppDbContext>(); if (db.Database.IsSqlite()) { Log.Information("No Postgres connection string provided, using Sqlite database provider"); } else { Log.Information("Using Npgsql database provider"); } if (!db.Database.CanConnect() && !db.Database.GetMigrations().Any()) { db.Database.EnsureCreated(); } else if (db.Database.GetMigrations().Any()) { db.Database.Migrate(); } if (db.Contacts.Any()) { return; } Log.Information("Seeding database"); var rand = new Random(); var numbers = DemoData.GetNumbers(); var contacts = DemoData.GetContacts(); foreach (var contact in contacts) { contact.PhoneNumbers = new List <PhoneNumber> { new PhoneNumber { Number = numbers[rand.Next(0, 999)] }, new PhoneNumber { Number = numbers[rand.Next(0, 999)] }, new PhoneNumber { Number = numbers[rand.Next(0, 999)] }, new PhoneNumber { Number = numbers[rand.Next(0, 999)] }, }; db.Contacts.Add(contact); } db.SaveChanges(); Log.Debug("Database seeding complete"); }