.NET 6 - Operate database by EFCore
Table of Contents
The Entity Framework (ADO.NET Entity Framework) is a set of technologies in ADO.NET. In the following article, I will introduce two methods, Database first and Code first, to Connect SQL Server DB in ASP.NET6 Web API by Entity Framework Core. Either one can achieve our goal. Let’s start!
DB First
Add Model
Package required

Open Package Manager Console

Use
Scaffold-DbContextto generate code for a DbContext and entity types from database.Scaffold-DbContext "Server=localhost\SQLEXPRESS;Database=AccountingCF;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir ModelsThis will create a class which extends
DbContextpublic partial class AccountingCFContext : DbContext { public NorthwindContext() {} public NorthwindContext(DbContextOptions<NorthwindContext> options) : base(options) {} public virtual DbSet<Record> Records { get; set; } = null!; modelBuilder.Entity<Record>(entity => {...}); }Also, Entity type
Record, which is a table in database.public partial class Record { public int RecordId { get; set; } public string Title { get; set; } = null!; public DateTime Date { get; set; } public int Genre { get; set; } public string? Description { get; set; } public int Amount { get; set; } }
Add ConnectionStrings
- Package required

- Add
ConnectionStringsin appsettings.json Set the database’s server location and the database’s name."ConnectionStrings": { "DefaultConnection": "Server=localhost\\SQLEXPRESS;Database=AccountingCF;Trusted_Connection=True;" } - Add db connection in Program.cs
builder.Services.AddDbContext<AccountingCFContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
- Package required
Add Controller
[Route("api/[controller]")]
[ApiController]
public class RecordController : ControllerBase
{
private readonly AccountingCFContext _dataContext;
public RecordController(AccountingCFContext context)
{
_dataContext = context;
}
[HttpGet]
public IEnumerable<Record> GetRecords()
{
return _dataContext.Record.ToList();
}
}
Code First
Add Models Folder create DbContext and Model class
- Record.cs
public class Record { public int RecordId { get; set; } public string Title { get; set; } = string.Empty; public DateTime Date { get; set; } = DateTime.Now; public RecordGenre Genre { get; set; } public string? Description { get; set; } public int Amount { get; set; } } public enum RecordGenre { Income, Expense } - Accounting.cs
using Microsoft.EntityFrameworkCore; public class AccountingContext : DbContext { public AccountingContext(DbContextOptions<AccountingContext> options) : base(options) {} public DbSet<Record> Record { get; set; } }
- Record.cs
ConnectionStrings
package required

Add
ConnectionStringsin appsettings.json Set the database’s server location and the database’s name."ConnectionStrings": { "DefaultConnection": "Server=localhost\\SQLEXPRESS;Database=AccountingCF;Trusted_Connection=True;" }Add db connection in Program.cs
builder.Services.AddDbContext<NorthwindContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
Add Migration
- Package required

Add-Migration InitialCreate
After the command is excuted, a new folder Migrations will be created.

- Look into class InitialCreate in InitialCreate.cs There is an
Upmethod to create table and aDownmethod to drop table.public partial class InitialCreate : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Record", columns: table => new { RecordId = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Title = table.Column<string>(type: "nvarchar(max)", nullable: false), Date = table.Column<DateTime>(type: "datetime2", nullable: false), Genre = table.Column<int>(type: "int", nullable: false), Description = table.Column<string>(type: "nvarchar(max)", nullable: true), Amount = table.Column<int>(type: "int", nullable: false) }, constraints: table => { table.PrimaryKey("PK_Record", x => x.RecordId); }); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Record"); } }
- Package required
Execute
Update-Database.- The command will create the database if it is not exsit.

- Open the SQL Server management to see the created database.

- The command will create the database if it is not exsit.
Reference
- Entity Framework Core tools reference
- CRUD with a .NET 6 Web API & Entity Framework Core
- Migrations Overview