Learn Programming, Tech & Coding · Free Online Tools

IT Question Answer
Back to .NET
Entity Framework Core Guide

Entity Framework Core Guide

.NET2,640 viewsBy Admin
dot-netentityframeworkcore

What is Entity Framework Core?

EF Core is Microsoft's ORM (Object-Relational Mapper). It lets you work with a database using C# objects instead of raw SQL.

Define a Model

public class Product {
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

The DbContext

public class AppDb : DbContext {
    public DbSet<Product> Products { get; set; }
}

CRUD with LINQ

// Create
db.Products.Add(new Product { Name = "Pen", Price = 2 });
await db.SaveChangesAsync();

// Read
var cheap = await db.Products.Where(p => p.Price < 5).ToListAsync();

// Update
product.Price = 3; await db.SaveChangesAsync();

// Delete
db.Products.Remove(product); await db.SaveChangesAsync();

Migrations

dotnet ef migrations add InitialCreate
dotnet ef database update

FAQs

Code-first or database-first?

Code-first (define C# classes, generate DB) is most popular for new apps. More in our .NET section.

Does EF support multiple databases?

Yes — SQL Server, PostgreSQL, MySQL, SQLite, and more via providers.