How to Use Entity Framework Core for Database Management in Full Stack .NET
How to Use Entity Framework Core for Database Management in Full Stack .NET
🔧 What is Entity Framework Core?
Entity Framework Core (EF Core) is an Object-Relational Mapper (ORM) for .NET. It enables developers to interact with a relational database using .NET objects instead of raw SQL queries. EF Core supports LINQ, migrations, and code-first or database-first development.
🔨 Prerequisites
.NET SDK
A relational database (e.g., SQL Server, SQLite, PostgreSQL)
A full-stack .NET project (e.g., ASP.NET Core + front end)
EF Core packages (install via NuGet or CLI)
🛠️ Step-by-Step Guide
1. Install EF Core Packages
Use NuGet Package Manager or the .NET CLI:
bash
Copy
Edit
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
Replace SqlServer with Sqlite, Npgsql, or others depending on your database.
2. Create Your DbContext Class
The DbContext is the central class that manages database connections and operations.
csharp
Copy
Edit
using Microsoft.EntityFrameworkCore;
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
public DbSet<Product> Products { get; set; }
}
3. Define Your Entity Classes
csharp
Copy
Edit
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
4. Configure EF Core in Startup
For ASP.NET Core:
csharp
Copy
Edit
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer("YourConnectionStringHere"));
services.AddControllersWithViews(); // or AddRazorPages()
}
}
For .NET 6+ (Minimal APIs):
csharp
Copy
Edit
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer("YourConnectionStringHere"));
var app = builder.Build();
// Configure app...
5. Add a Migration and Update Database
Create an initial migration:
bash
Copy
Edit
dotnet ef migrations add InitialCreate
Apply migration to create the database:
bash
Copy
Edit
dotnet ef database update
6. Perform CRUD Operations
Example: Add a new product
csharp
Copy
Edit
using (var context = new AppDbContext(options))
{
var product = new Product { Name = "Book", Price = 9.99M };
context.Products.Add(product);
context.SaveChanges();
}
Query with LINQ:
csharp
Copy
Edit
var allProducts = context.Products.ToList();
7. Connect to Front End (Optional)
If you're using React, Angular, or Blazor as a front end:
Use Web API controllers to expose endpoints.
Consume those endpoints from your front-end code.
csharp
Copy
Edit
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
private readonly AppDbContext _context;
public ProductsController(AppDbContext context)
{
_context = context;
}
[HttpGet]
public async Task<ActionResult<IEnumerable<Product>>> GetProducts()
{
return await _context.Products.ToListAsync();
}
}
✅ Best Practices
Use async/await for database operations (SaveChangesAsync, ToListAsync, etc.)
Use migrations to manage schema changes
Use dependency injection for the DbContext
Enable logging during development for debugging SQL queries
Apply validation and data annotations on your models
🧩 Summary
Feature EF Core Usage
ORM Yes (code-first, database-first, or model-first)
Database Support SQL Server, SQLite, PostgreSQL, MySQL, etc.
Migrations dotnet ef migrations
CRUD Operations LINQ and DbSet methods
Integration with Web API Seamless with ASP.NET Core
Learn Full Stack Dot NET Training in Hyderabad
Read More
Building RESTful APIs with ASP.NET Core Web API
Visit Our Quality Thought Training in Hyderabad
Comments
Post a Comment