Book Image

Mastering Entity Framework Core 2.0

By : Prabhakaran Anbazhagan
Book Image

Mastering Entity Framework Core 2.0

By: Prabhakaran Anbazhagan

Overview of this book

Being able to create and maintain data-oriented applications has become crucial in modern programming. This is why Microsoft came up with Entity Framework so architects can optimize storage requirements while also writing efficient and maintainable application code. This book is a comprehensive guide that will show how to utilize the power of the Entity Framework to build efficient .NET Core applications. It not only teaches all the fundamentals of Entity Framework Core but also demonstrates how to use it practically so you can implement it in your software development. The book is divided into three modules. The first module focuses on building entities and relationships. Here you will also learn about different mapping techniques, which will help you choose the one best suited to your application design. Once you have understood the fundamentals of the Entity Framework, you will move on to learn about validation and querying in the second module. It will also teach you how to execute raw SQL queries and extend the Entity Framework to leverage Query Objects using the Query Object Pattern. The final module of the book focuses on performance optimization and managing the security of your application. You will learn to implement failsafe mechanisms using concurrency tokens. The book also explores row-level security and multitenant databases in detail. By the end of the book, you will be proficient in implementing Entity Framework on your .NET Core applications.
Table of Contents (20 chapters)
Title Page
Credits
About the Author
About the Reviewers
www.PacktPub.com
Customer Feedback
Dedication
Preface
4
Building Relationships – Understanding Mapping

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