Click here to Skip to main content
15,886,830 members
Articles / Database Development

Entity Framework 7 – Code First – Using CLI

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
1 Jun 2023CPOL3 min read 7.3K   73   12   4
Tutorial on EF7 – Code First approach using Command Line (CLI)
In this article, we show 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.

1. Introduction

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

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

2. Sample Project

2.1. Sample Console .NET7 Application

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

Image 1

C#
//=====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, that is 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 first created the Entity class, and then we will create database tables from the code. For that, we need tools, in this case, CLI EF Core tools.

2.2. SqlServer Database

We have SqlServer ready and have configured the database connection string in appsettings.json file which will be used for creation of the database.

3. Installing CLI EF Core Tools

You need to 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 the screenshots:

Image 2

Image 3

4. Creating the Database

4.1. Step 1 - Creating Migration

Now is the time to do the 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:

Image 4

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

Image 5

4.2. Step 2 – Creating the Database

To actually 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:

Image 6

And here is the result.

Image 7

The SqlServer database Test1 has been created and in it table Persons.

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

Image 8

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

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

6. Upgrading Database

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

Image 9

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

Image 10

6.2. Step 2 – Updating the Database

To actually 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:

Image 11

And here is the result:

Image 12

The SqlServer database Test1, in it table Persons, column Profession has been created.

Note also, the database table __EFMigrationsHistory tracks which migrations have been applied.

Image 13

7. Testing Application

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

C#
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:

Image 14

And here is the database table Persons:

Image 15

8. Conclusion

We showed how “Code First” database generation from 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.

9. References

10. History

  • 2nd June, 2023: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Serbia Serbia
Mark Pelf is the pen name of just another Software Engineer from Belgrade, Serbia.
My Blog https://markpelf.com/

Comments and Discussions

 
QuestionGot error NU1301: Failed to retrieve information about 'dotnet-ef' Pin
Rod at work7-Jun-23 9:11
Rod at work7-Jun-23 9:11 
QuestionIntelliSense Pin
Jeff Bowman5-Jun-23 20:27
professionalJeff Bowman5-Jun-23 20:27 
AnswerRe: IntelliSense Pin
Mark Pelf 5-Jun-23 20:38
mvaMark Pelf 5-Jun-23 20:38 
GeneralRe: IntelliSense Pin
Jeff Bowman5-Jun-23 20:41
professionalJeff Bowman5-Jun-23 20:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.