Articles → ASP.NET CORE → Create a database and table from a code-first approach in asp.net core

Create a database and table from a code-first approach in asp.net core






Package installation




  1. Microsoft.EntityFrameworkCore
  2. Microsoft.EntityFrameworkCore.SqlServer
  3. Microsoft.EntityFrameworkCore.Tools
  4. Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation

Add Connection string in appsettings.json




Picture showing the connection string in the appsettings.json file

Click to Enlarge


Add Model class






using System.ComponentModel.DataAnnotations;

namespace BookManagementSystem.Model {
  public class Book {
    [Key]
    public int Id {
      get;
      set;
    }

    [Required]
    public string Name {
      get;
      set;
    }

    public string Author {
      get;
      set;
    }
  }
}



Create DbContext class




using Microsoft.EntityFrameworkCore;

namespace BookManagementSystem.Model {
  public class ApplicationDbContext: DbContext {
    public ApplicationDbContext(DbContextOptions < ApplicationDbContext > options): base(options) {

    }

    public DbSet < Book > Book {
      get;
      set;
    }
  }
}



Add ApplicationDbContext in startup.cs




  1. Import "Microsoft.EntityFrameworkCore";
  2. Inside the "ConfigureServices" method, add the following code.
services.AddDbContext<ApplicationDbContext>(option => option.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));



Run migration command




  1. Open package manager console. For that go to "Tools" → "NuGet Package Manager" → "Package Manager Console".
  2. Inside it write the following command
  3. add-migration AddBookToDb




  4. Then execute the following command
update-database




Picture showing the table created from the code first approach in asp.net core

Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Wednesday, March 31, 2021

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250