Enabling Code First in asp.net Core MVC (Entity framework Core)

This tip can be used to enable code first in entity framework core. By using the following steps.
  • Create new asp.net MVC Core project 
  • install the required Nuget packages as shown in Screen shot.
  • Create Database (MyDb) in sql server.
  • put connection string in (appsettings.json) 

appsettings.js should look like this
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "ConnectionStrings": {
    "MyDbConnection": "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=MyDB;Data Source=(local)"
  },
  "AllowedHosts": "*"
}
  • Add tblTest class to Models folder (tblTest.cs)
  • Add DbContext class to Models folder (MyDbContext.cs)
  • Both Classes should look like the following
tblTest.cs
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace MyCoreProject.Models
{
    public class tblTest
    {
        [Key]        
        public int ID { get; set; }
        public string Name { get; set; }
    }
}

MyDbContext.cs
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace MyCoreProject.Models
{
    public class MyDbContext:DbContext
    {
        public MyDbContext():base()
        {

        }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                IConfigurationRoot configuration = new ConfigurationBuilder()
                   .SetBasePath(Directory.GetCurrentDirectory())
                   .AddJsonFile("appsettings.json")
                   .Build();               
                optionsBuilder.UseSqlServer(configuration.GetConnectionString("MyDbConnection") );
            }

        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }
        DbSet<tblTest> tblTests { get; set; }

    }
}
  • Now Click on tools->NuGet Package Manager->Package Manager Console
  • Write the following command
PM> add-migration first
After running this command new folder (Migrations) will be added to your project. including two classes (MyDbContextModelSnapshot.cs, 20210211101858_first.cs )
20210211101858_first.cs
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
using Microsoft.EntityFrameworkCore.Migrations;

namespace MyCoreProject.Migrations
{
    public partial class first : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                name: "tblTests",
                columns: table => new
                {
                    ID = table.Column<int>(type: "int", nullable: false)
                        .Annotation("SqlServer:Identity", "1, 1"),
                    Name = table.Column<string>(type: "nvarchar(max)", nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_tblTests", x => x.ID);
                });
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable(
                name: "tblTests");
        }
    }
}
Now run the following command in nuget package manager console
PM> update-database
After running the above command. Open sql server management studio expand the database (MyDb) you will notice a new table (tblTests) is added to tables

Post a Comment