Monday, 15 February 2021

Starting Entity Framework Core with Code First

On this post we will see how to use Code First development with EntityFramework Core and SQL Server.

Add Microsoft.EntityFrameworkCore.SqlServer (current version at time of writing is v5.0.2) in Package Manager.

Create the model class:
public class Trainee
{
    public long TraineeId { get; set; }
    public string Firstname { get; set; }
    public string Lastname { get; set; }
}

Then create a context class derived from DbContext:
public class TraineeBoundedContext : DbContext
{
    public DbSet<Trainee> Trainees { get; set; }

    /* using default constructor is enough
    public TraineeBoundedContext(DbContextOptions<TraineeBoundedContext> options) : base(options)
    {
    }*/
    
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("Server=YOUR_SERVER_NAME;Database=YOUR_DATABASE_NAME;Integrated Security=True");  // put your server and database names
    }
}

Add Microsoft.EntityFrameworkCore.Tools (current version at time of writing is v5.0.3) package for EF migration feature.

Then run 'Add-Migration MIGRATION_NAME' command on Package Manager Console:
PM> Add-Migration InitialMigration
Build started...
Build succeeded.
To undo this action, use Remove-Migration.

It will create some files. In my case, I chose 'InitialMigration' as the name.

One of the generated file shows this:

Then we can apply this to the database with 'Update-Database' command.
PM> update-database
Build started...
Build succeeded.
Applying migration '20210212053620_InitialMigration'.
Done.

When you check your database, it should have new tables:

No comments: