Created
December 3, 2018 00:29
-
-
Save rodrigolira/fa1c927dbb68ee97023f3a63290acec4 to your computer and use it in GitHub Desktop.
Seeding data on Asp.Net Core 2.0
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MyDatabaseSeeder | |
{ | |
public static async Task SeedAsync(MyDbContext context) | |
{ | |
if(!context.Foos.Any()) | |
{ | |
context.Foos.AddRange(GetPreconfiguredFoos()); | |
await context.SaveChangesAsync(); | |
} | |
if(!context.Bars.Any()) | |
{ | |
context.Bars.AddRange(GetPreconfiguredBars()); | |
await context.SaveChangesAsync(); | |
} | |
} | |
static IEnumerable<Foo> GetPreconfiguredFoos() { | |
return new List<Foo>() | |
{ | |
new Foo() { Id = 1, Name = "Foo" } | |
}; | |
} | |
static IEnumerable<Bar> GetPreconfiguredBars() { | |
return new List<Bar>() | |
{ | |
new Bar() { Id = 1, Name = "Bar" } | |
}; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
var host = BuildWebHost(args); | |
using (var scope = host.Services.CreateScope()) | |
{ | |
var services = scope.ServiceProvider; | |
try | |
{ | |
var context = services.GetRequiredService<MyDbContext>(); | |
MyDatabaseSeeder.SeedAsync(context).Wait(); | |
} | |
catch (Exception ex) | |
{ | |
var logger = services.GetRequiredService<ILogger<Program>>(); | |
logger.LogError(ex, "An error occured while seeding the database"); | |
} | |
} | |
host.Run(); | |
} | |
public static IWebHostBuilder CreateWebHostBuilder(string[] args) => | |
WebHost.CreateDefaultBuilder(args) | |
.UseStartup<Startup>(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment