EF Core – Code First with existing database ASP.NET Core

In ASP.NET Core using a Entity Framework Core we only have the option to connect with a database by aproach code first. Edmx and Dbml will not be supported anymore.
So what to do if we have existing database and we want to create a model based on EF Core in application.

I’ll show you in a short tutorial how to get it with the easiest way.

Example

At the first we need to create class which is a reflection of the property in the database table.

tableDb

public class SomeTable
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
}

Then we need to create a class that will inherit from DbContext from the namespace EntityFrameworkCore and it will contain the properties of our table / tables.

public class SomeContext : DbContext
{
    public DbSet<SomeTable> SomeTable{ get; set; }
    public SomeContext(DbContextOptions<SomeContext> options) : base(options)
    {
    }
}

Configure a connection to the database with a default connection string  from appsettings.json in the startup class.

            services.AddDbContext<SomeContext>(x =>
                                 x.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
  "ConnectionStrings": {
    "DefaultConnection": "server=.\\SQLEXPRESS;Database=ExampleDb;Trusted_Connection=True;"
  }

Add migrations by use command Add-Migrations.

The following class was generated by migrations

public partial class firstmigration : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.CreateTable(
            name: "SomeTable",
            columns: table => new
            {
                Id = table.Column<int>(nullable: false)
                    .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                Name = table.Column<string>(nullable: true),
                Surname = table.Column<string>(nullable: true)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_SomeTable", x => x.Id);
            });
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropTable(
            name: "SomeTable");
    }
}

We have to delete everything that is in the function “Up”. And use command Update-Database. After these operations, we have a generated migration and finally, we can “normally” use the code first approach without any conflicts.

example2

Link to the project.

Leave a Reply

Your email address will not be published. Required fields are marked *