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 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"
- Inside the "ConfigureServices" method, add the following code
services.AddDbContext<ApplicationDbContext>(option => option.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
Run Migration Command
- Open package manager console. For that go to "Tools" → "NuGet Package Manager" → "Package Manager Console".
- Inside it write the following command
add-migration AddBookToDb
- Then execute the following command
Click to Enlarge