05_Code First Approach - Maniconserve/EF-Core GitHub Wiki
Code First approach in Entity Framework allows you to define database tables using C# classes instead of designing the database first. The database is automatically created based on the model classes and can be updated using migrations.
To use the Code First approach in a .NET Console Application, install the necessary NuGet packages:
Install-Package Microsoft.EntityFrameworkCore
Install-Package Microsoft.EntityFrameworkCore.SqlServer
Install-Package Microsoft.EntityFrameworkCore.Tools
Create an entity class representing a database table.
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
Define a context class that inherits from DbContext and reads the connection string from a configuration file.
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System.IO;
public class SchoolContext : DbContext
{
public DbSet<Student> Students { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
string connectionString = configuration.GetConnectionString("DefaultConnection");
optionsBuilder.UseSqlServer(connectionString);
}
}
Create an appsettings.json file in the project root and define the connection string.
{
"ConnectionStrings": {
"DefaultConnection": "Server=YOUR_SERVER;Database=SchoolDB;Trusted_Connection=True;"
}
}
Use Entity Framework commands to create and apply migrations.
PM> Add-Migration students
When a migration is created, a generated C# file is produced with the specified migration name. This file contains Up and Down methods, which define the changes applied to the database and the actions needed to revert those changes, respectively.
PM> Update-Database
we can see the table created in the respective database
After creating a table, you might need to modify it by adding a new column, making a column nullable, setting it as non-nullable, renaming it, etc. Below are different modifications and how to apply them using migrations.
- Remove the property from the entity class.
- Run migration and update the database.
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
// public int Age { get; set; } // Remove this line to drop the column
}
add-migration RemoveAgeColumn
update-database
Generated Migration:
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Age",
table: "Students");
}
- Add a new property to the entity.
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; } // New column added
}
add-migration AddAgeColumn
update-database
Generated Migration:
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "Age",
table: "Students",
nullable: false,
defaultValue: 0);
}
- Modify the property in the entity to allow null.
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int? Age { get; set; } // Made nullable
}
add-migration MakeAgeNullable
update-database
Generated Migration:
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<int?>(
name: "Age",
table: "Students",
nullable: true);
}
- Modify the property in the entity to not allow nulls.
- Set a default value in migration to avoid errors.
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; } // Made non-nullable
}
add-migration MakeAgeNotNullable
update-database
Generated Migration:
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<int>(
name: "Age",
table: "Students",
nullable: false,
defaultValue: 18); // Default value to prevent null errors
}
If you want to rename a column, you need to keep the existing property and use migration commands.
add-migration RenameAgeToStudentAge
update-database
Generated Migration:
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(
name: "Age",
table: "Students",
newName: "StudentAge");
}
Modify the property type in the entity.
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string Age { get; set; } // Changed from int to string
}
add-migration ChangeAgeType
update-database
Generated Migration:
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<string>(
name: "Age",
table: "Students",
nullable: false);
}
These are different modifications you can apply to your Code First database schema.