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 A 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. Add the following code inside the ConfigureServices method.
services.AddDbContext<ApplicationDbContext>(option => option.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));




Run Migration Command




  1. Navigate to ToolsNuGet Package ManagerPackage Manager Console.
  2. Write the following command.
  3. add-migration AddBookToDb





  4. Then execute the following command
  5. 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
 
Updated On  -  Wednesday, January 26, 2022

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250