Application data
.NET Core ASP.NET Core C# Entity Framework Core Fluent Assertion SQL Visual Studio

Using Entity Framework Core in a .NET Core Application

In this post I will show you how to create the data layer for your .NET Core application using the Entity Framework Core (EF Core) package.

First of all, ensure that you have installed the Microsoft.AspNetCore.All (2.0.x) package from the NuGet Package Manager:

After installation, expand out the Dependencies folder in your solution.

You should (see after scrolling down) the EF Core packages Microsoft.EntityFrameworkCore.* that will be utilized for EF Migration, Schema creation and run-time use.

Next, I will show how to create a new Database using EF Code First:

At this point there are no defined table data structures. We create the initial database as follows:

Step 1 – Create the Initial Database Based on the Db Context

Open PowerShell console within Visual Studio.

Run the following command:

Add-Migration InitialCreate

Next, run the command:

Update-Database

This will create the initial database.

Step 2 – Check database created

Open your app settings appsettings.json and check the connection strings are there:

  "ConnectionStrings": {
    "AppDbContext": "Server=(localdb)\\mssqllocaldb;Database=aspnet-BookLoan-7939A8EF-89B2-46F3-9E64-E33629F164CB;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
..

Also, you will need to configure your connection string to be injected into the database options of the data context. This is done by adding the line of code in the ConfigureServices() Startup method as shown below:

services.AddDbContext<ApplicationDbContext>(
   options =>
 options.UseSqlServer(
      Configuration.GetConnectionString("AppDbContext")));

(Refer to https://docs.microsoft.com/en-us/ef/core/miscellaneous/configuring-dbcontext for more details.)

The data context is defined within a context class definition ApplicationDbContext.cs. Within this context class, the overridden method  OnModelCreating(), which is from the abstract DbContext class within EF Core contains commands used to build the table schemas and relationships for your application.

using Microsoft.EntityFrameworkCore;

public class ApplicationDbContext: DbContext
{
        public ApplicationDbContext( DbContextOptions<ApplicationDbContext> options)
: base(options)
        { }

        protected override void OnModelCreating(ModelBuilder builder)
        {
           base.OnModelCreating(builder);
	       // Place any EF schema definitions here
                  ...
}

This context code is usually in a subfolder in your project (in this case named by default Data). When the context is instantiated, the connection string is passed into the context via the options parameter.

Now open SSMS and open the server folder and the new database will show.

The next few steps will demonstrate how to add a basic table to the database.

Step 3 – Define the Model

Each custom table created within EF Code First, will require a model class definition before it can be declared and staged for creation.

In this example, we create a new table called BookViewModel as a C# class, which will define the model for the table.

A definition like this with property accessors will achieve the goal:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace BookLoan.Models
{
    public class BookViewModel
    {
        public int ID { get; set; }
        [Required]
        public string Title { get; set; }
        [Required]
        public string Author { get; set; }
        public int YearPublished { get; set; }
        public string Genre { get; set; }
        public string Edition { get; set; }
        public string ISBN { get; set; }
        [Required]
        public string Location { get; set; }
        public DateTime DateCreated { get; set; }
        public DateTime DateUpdated { get; set; }
    }
}

Step 4 – Define the Table Schema

Entering the following command within the OnModelCreating() method below the base.OnModelCreating() line in ApplicationDbContext.cs will define our table schema:

builder.Entity<BookViewModel>().ToTable("Books");

Save the change.

Step 5 – Apply the EF Code First migration

Open PowerShell console within Visual Studio.

Run the following command (or similar):

Add-Migration add_bookloan_tables_05_11_2019

[where add_bookloan_tables_05_11_2019 = name of your migration]

After this command is run, in your project \Domain folder you will see a new sub-folder \Migrations created which will contain the schema changes to your database. This is what EF Core will use to help migration your changes across to the database.

Note: To undo changes run:

Remove-Migration

This command will not work after Update-Database is run.

Next, run the command:

Update-Database

This will commit the schema changes to the database.

When completed, open the SQL Explorer or SSMS. Open server localdb)\MSSQLLocalDB.

Expand the tables and you should see the identity tables created as shown:

Notice there is also __EFMigrations history table. This is used to track each migration into the current database.

Run a SQL select on this table and you will see:

Notice that the MigrationId column contains the corresponding Migration generated by EF Core Code First.

So, 20191105080658_add_bookloan_tables_05_11_2019

Corresponds to the generated partial Migration class as shown:

That’s all for now.

I hope this post has been informative. In a later post I will discuss how to make changes to your schema using EF Core.

Bye!

Social media & sharing icons powered by UltimatelySocial