Entity Framework 7 Code First Using CLI

Abstract: In this article, we are showing how to practically implement the “Code First” approach in Entity Framework Core 7 using Command Line (CLI). The database can be created from Entity Framework Model using CLI EF Core tools.

Introduction

Entity Framework Core is giving preference to the “Code First” approach that enables the database creation from Entity Framework Model using the command line “CLI EF Core tools”. This article outlines practical steps to create a database and enumerate necessary command line commands to “migrate/update” the database after changes in the code.

EFCorePowerTools

This article would not be complete without mentioning the EFCorePowerTools [3], which is a GUI “community open source” tool with the aim to support operations related to EF. At the time of writing (May 2023), they offer just some “preview” features and are not practically usable for our “Code First” approach here. Here we focus on the “official” command line interface (CLI) approach.

Sample Console .NET7 application

We created a sample Console .NET7 application which we will use. Here is the screenshot of the application and then the code.

Entity Framework 7 Code First Using CLI

//=====Person.cs========================================
 public class Person
    {
        public int Id { get; set; }
        public string? Name { get; set; }
        public int Age { get; set; }
        public string? Address { get; set; }
    }

//=====Test1DbContext.cs====================================
public class Test1DbContext : DbContext
    {
        public Test1DbContext(DbContextOptions<Test1DbContext> options)
            : base(options)
        {
        }
        public DbSet<Person> Persons { get; set; }
    }
	
//=====Test1DbContextFactory.cs=============================
public class Test1DbContextFactory : IDesignTimeDbContextFactory<Test1DbContext>
    {
        static Test1DbContextFactory()
        {
            IConfiguration config = new ConfigurationBuilder()
               .SetBasePath(Directory.GetCurrentDirectory())
               .AddJsonFile("appsettings.json", true, true)
               .Build();

            connectionString = config["ConnectionStrings:Test1Connection"];
            Console.WriteLine("ConnectionString:" + connectionString);
        }

        static string? connectionString = null;

        public Test1DbContext CreateDbContext(string[] args)
        {
            var optionsBuilder = new DbContextOptionsBuilder<Test1DbContext>();

            optionsBuilder.UseSqlServer(connectionString);

            return new Test1DbContext(optionsBuilder.Options);
        }
    }
	
//=====appsettings.json============================
{
  "ConnectionStrings": {
    "Test1Connection": "Data Source=.;User Id=sa;Password=dbadmin1!;Initial Catalog=Test1;Encrypt=False"
  }
}
//============================

As you can see, we created only one EntityDataModel class, “Person”. Our context Test1DbContext contains only one DbSet<> property “Persons”. The corresponding planned result will be a database named “Test1” with only one database table, “Persons”.

That is the “Code First” approach in which we create the Entity class and then create database tables from the code. For that, we need tools, in this case, “CLI EF Core tools”.

SqlServer database

We have SqlServer ready and have configured the database connection string in the appsettings.json file, which will be used to create the database.

Installing CLI EF Core tools

You must install CLI EF Core tools and navigate to the project folder. Here are the commands you will need.

dotnet tool uninstall --global dotnet-ef
dotnet tool install --global dotnet-ef --version 7.0.5
cd C:\Tmp\Example3\Example3\

Here are screenshots:

Entity Framework 7 Code First Using CLI

Entity Framework 7 Code First Using CLI

Creating the database


Step 1. Creating Migration

Now is the time to do actual work. The first thing you need to do is create the migration files. You will need the following command:

// This will create .cs migration files in the directory Migration
// Note that "Initial" is an arbitrary name

dotnet ef migrations add Initial -o Migrations -c Example3.Test1DbContext

Here is the execution:

Entity Framework 7 Code First Using CLI

And here is the result. Note that the “Migration” folder has been created with migration files.

Entity Framework 7 Code First Using CLI

Step 2. Creating the database

To create the database, you will need the following command:

// This will apply all migrations to database that are not 
// already applied. It will create the database if needed. 

dotnet ef database update -c Example3.Test1DbContext

Here is the execution:

Entity Framework 7 Code First Using CLI

And here is the result.

Entity Framework 7 Code First Using CLI

The SqlServer database “Test1” has been created and in its table “Persons”.

Note. Also, the database table “__EFMigrationsHistory” has been created, and it tracks which migrations have been applied.

Changing code/ Entity Data Model

A typical situation is that you want to change your Entity Data Model over time. Here we will illustrate it by adding one new property to the class “Person”. We will add the property “Profession” to the class.

public class Person
    {
        public int Id { get; set; }
        public string? Name { get; set; }
        public int Age { get; set; }
        public string? Address { get; set; }
        public string? Profession { get; set; }
    }

Now we have a situation the code (Entity Data Model) is out of synchronization with the database. We need to address that.

Upgrading database


Step 1. Creating Migration

The first thing you need to do is create the migration files. You will need the following command:

// This will create .cs migration files in the directory Migration
// Note that "Work" is an arbitrary name

dotnet ef migrations add Work -o Migrations -c Example3.Test1DbContext

Here is the execution:

Entity Framework 7 Code First Using CLI

And here is the result. Note that in the “Migration” folder, file “20230530053706_Work.cs” has been created.

Entity Framework 7 Code First Using CLI

Step 2. Updating the database

To update the database, you will need the following command:

// This will apply all migrations to database that are not 
// already applied. It will create the database if needed. 

dotnet ef database update -c Example3.Test1DbContext

Here is the execution:

Entity Framework 7 Code First Using CLI

And here is the result.

Entity Framework 7 Code First Using CLI

The SqlServer database “Test1”, in its table “Persons”, column “Profession” has been created.

Note. Also the database table “__EFMigrationsHistory” tracks which migrations have been applied.

Entity Framework 7 Code First Using CLI

Testing application

We will create some code to test our EF-generated model. Here is the test code:

using Example3.EntityDataModel;
using Example3;

Console.WriteLine("Hello from Example3");

using Test1DbContext ctx = new Test1DbContextFactory().CreateDbContext(new string[0]);

Person per1 = new Person { Name = "Mark", Age = 33, Address = "Belgrade, Serbia", Profession = "Programmer" };

ctx.Persons.Add(per1);
ctx.SaveChanges();

Console.WriteLine("Table Persons ==================================");
foreach (var person in ctx.Persons)
{
    Console.WriteLine("Id:" + person.Id.ToString() + " Name:" + person.Name);
}

And here is the execution result:

Entity Framework 7 Code First Using CLI

And here is the database table “Persons”

Entity Framework 7 Code First Using CLI

Conclusion

We showed how “Code First” database generation from the EF model works from the command line (CLI) using CLI EF Core tools. The process is not difficult, although not that intuitive.

At the time of writing (May 2023), the GUI “community open source” tool EFCorePowerTools does not support Migrations in the “Code First” approach.

References


Similar Articles