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
  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