09 Sep Entity Framework 7 – Code First – Using CLI
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.
1 Introduction
Entity Framework Core is giving preference to “Code First” approach that enables the database creation from Entity Framework Model using the command line “CLI EF Core tools”. This article has aim 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 and then the code.
//=====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 screenshots:
4 Creating the database
4.1 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:
And here is the result. Note that the “Migration” folder has been created with migration files in it.
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:
And here is the result.
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.
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.
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:
And here is the result. Note that in the “Migration” folder file “20230530053706_Work.cs” has been created.
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:
And here is the result.
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.
29_pic67.png
7 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:
And here is the database table “Persons”
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
[1] https://learn.microsoft.com/en-us/ef/core/cli/
[2] https://learn.microsoft.com/en-us/ef/core/managing-schemas/scaffolding/?tabs=dotnet-core-cli
[3] https://github.com/ErikEJ/EFCorePowerTools/
[4] https://www.entityframeworktutorial.net/efcore/working-with-stored-procedure-in-ef-core.aspx
Sorry, the comment form is closed at this time.