We have created an empty database, and we should have a mechanism by which we can seed the initial/master data that might be required by the web application. In our case, we don't have any master data, so all we can do is create a couple of blogs and corresponding posts. We need to ensure whether the database was created or not before we start adding data to it. The EnsureCreated method helps us in verifying this. Create a new DbInitializer.cs class file inside the Data folder and include the following code:
public static void Initialize(BlogContext context)
{
context.Database.EnsureCreated();
// Look for any blogs.
if (context.Blogs.Any())
{
return; // DB has been seeded
}
var dotnetBlog = new Blog {
Url = "http://blogs.packtpub.com/dotnet" };
var dotnetCoreBlog = new Blog { Url =
"http://blogs.packtpub.com/dotnetcore" };
var blogs = new Blog[]
{
dotnetBlog,
dotnetCoreBlog
};
foreach (var blog in blogs)
{
context.Blogs.Add(blog);
}
context.SaveChanges();
var posts = new Post[]
{
new Post{Id= 1,Title="Dotnet 4.7 Released",Blog = dotnetBlog,
Content = "Dotnet 4.7 Released Contents", PublishedDateTime =
DateTime.Now},
new Post{Id= 1,Title=".NET Core 1.1 Released",Blog=
dotnetCoreBlog,
Content = ".NET Core 1.1 Released Contents", PublishedDateTime
=
DateTime.Now},
new Post{Id= 1,Title="EF Core 1.1 Released",Blog=
dotnetCoreBlog,
Content = "EF Core 1.1 Released Contents", PublishedDateTime =
DateTime.Now}
};
foreach (var post in posts)
{
context.Posts.Add(post);
}
context.SaveChanges();
}
In Program.cs, initialize DbInitializer in Main() by creating the BlogContext using dependency injection and pass the same to the DbInitializer.Initialize():
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<BlogContext>();
DbInitializer.Initialize(context);
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred initializing
the database.");
}
}
host.Run();
}
One last piece of the puzzle is missing; we need to add migration whenever we add/manipulate data models, without which EF doesn't know how the database needs to be created/updated. The migration can be performed with the NuGet Package Manager console:
Add-Migration InitialMigration
The preceding statement allows EF to create a migration file with tables created from the models configured in the DbContext. This can be done as follows:
Update-Database
The preceding statement applies the migration created to the database. At this moment we are almost done with the EF configuration. We should run the application and verify the database regarding whether or not the proper schema and seed data were updated.
We could verify the table whether it contains seeded data using the following SQL Server Object Explorer:
Database created successfully
We can see that the schema was created properly inside the MSSQLLocalDB instance, and we should expand the tables and verify whether the seed data was updated or not. The seed data of the Blog entity was updated properly, which was verified with the following screenshot:
Blog table created with configured schema and seed data
The seed data of the Post entity was updated properly, which was verified with the following screenshot.
Post table created with configured schema and seed data
We have ensured that the database was created with the proper schema and seed data, and now we should start consuming the entities. In the next section, let's see how we can consume the entities in MVC using scaffolding rather than building everything on our own.