Creating and seeding databases

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 ...

Get Mastering Entity Framework Core 2.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.