Create migration
Create migration
Use the below CLI command to create a migration which will intern create the database, the tables and the required columns in it as per the model we created
Add a migration
dotnet ef migrations add InitialCreate
We should now be able to see a migrations folder and a few files in it as shown

If we open the first file inside the migrations folder, we should see generated code which looks like this
public partial class InitialCreate : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Students",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(type: "nvarchar(max)", nullable: false),
IsEnrolled = table.Column<bool>(type: "bit", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Students", x => x.Id);
});
}
So, what exactly happened in the migration?
First, the migration command searched our project for a file or a class which derives from DbContext
once it found that it looked into the contents, especially a property or a set of properties of type DbSet<T>
It understood that they are our model files, and it needs to create database tables for the models by further looking at the properties of the model, which is
Student
in our caseIt further created the C# code required to programmatically create them
It has also done the mapping of C sharp data types to their respective SQL Server column types
Apply the migration
At this stage we have no database or tables created we can now do it by running the following cli command
dotnet ef database update
Once the above command runs successfully, we see that the database, tables and the columns are created accordingly

At this point we only have the table but no records inside it. Next, we will see how to create data.
Last updated