IConfiguration vs IOptions NET
Synchronous and Asynchronous in .NET Core
Model Binding and Validation in ASP.NET Core
ControllerBase vs Controller in ASP.NET Core
ConfigureServices and Configure methods
IHostedService interface in .NET Core
ASP.NET Core request processing
| Entity Framework Core | Entity Framework Core, DB first | |
ποΈ Entity Framework Core - Code First Approach |
Code First is an approach in Entity Framework Core where you define your domain models (C# classes) first, and EF Core generates the database schema from these classes. You can then use migrations to create, update, and maintain the database schema in sync with your code.
Hereβs a simple Code First example with EF Core:
// Install-Package Microsoft.EntityFrameworkCore
// Install-Package Microsoft.EntityFrameworkCore.SqlServer
// Install-Package Microsoft.EntityFrameworkCore.Tools
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
// Step 1: Define Model
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
// Step 2: Define DbContext
public class AppDbContext : DbContext
{
public DbSet<Product> Products { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Server=.;Database=CodeFirstDemo;Trusted_Connection=True;");
}
}
// Step 3: Usage
public class Program
{
public static async Task Main()
{
using var context = new AppDbContext();
// Apply migrations (from Package Manager Console):
// Add-Migration InitialCreate
// Update-Database
// Create
context.Products.Add(new Product { Name = "Laptop", Price = 1200 });
await context.SaveChangesAsync();
// Read
var products = await context.Products.ToListAsync();
foreach (var p in products)
Console.WriteLine($"{p.Id}: {p.Name} - {p.Price}");
}
}
EF Core Code First is ideal when starting fresh with a new project. It lets you design your domain model in C# and automatically generates the database schema. With migrations, you can evolve your schema safely while keeping your code and database in sync.
| Entity Framework Core | Entity Framework Core, DB first | |