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
- Microsoft.EntityFrameworkCore
- Microsoft.EntityFrameworkCore.SqlServer
- Microsoft.EntityFrameworkCore.Tools
- Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation
Add Connection String In Appsettings.Json
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
- Import Microsoft.EntityFrameworkCore.
- Add the following code inside the ConfigureServices method.
services.AddDbContext<ApplicationDbContext>(option => option.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
Run Migration Command
- Navigate to Tools → NuGet Package Manager → Package Manager Console.
- Write the following command.
add-migration AddBookToDb
- Then execute the following command
Click to Enlarge
Posted By - | Karan Gupta |
|
Posted On - | Wednesday, March 31, 2021 |
|
Updated On - | Wednesday, January 26, 2022 |