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.

Step 1: Install Required Packages

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

image

Step 2: Create Model Class

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; }
}

Step 3: Create a DbContext Class

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);
    }
}

Step 4: Configure Connection String in appsettings.json

Create an appsettings.json file in the project root and define the connection string.

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=YOUR_SERVER;Database=SchoolDB;Trusted_Connection=True;"
  }
}

Step 5: Create and Apply Migrations

Use Entity Framework commands to create and apply migrations.

PM> Add-Migration students

image

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.

image

PM> Update-Database

image

we can see the table created in the respective database

image

Step 6: Modifying an Existing Table in Code First Approach

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.


1. Dropping a Column

  • 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");  
}  

2. Adding a New Column

  • 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);  
}  

3. Making an Existing Column Nullable

  • 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);  
}  

image


4. Making an Existing Column Non-Nullable

  • 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  
}  

image


5. Renaming a Column

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");  
}  

6. Changing Column Data Type

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);  
}  

image


These are different modifications you can apply to your Code First database schema.

⚠️ **GitHub.com Fallback** ⚠️