What is an ORM?
🎯 What You'll Learn
- What ORM stands for
- Why use an ORM
- What is Entity Framework Core
- EF Core vs ADO.NET
- Database providers
- When to use EF Core
What is an ORM?
ORM stands for Object-Relational Mapping. It's a technique that lets you interact with a database using object-oriented code instead of writing SQL.
using var connection = new SqlConnection(connectionString);
connection.Open();
var command = new SqlCommand("SELECT * FROM Products WHERE Id = @id", connection);
command.Parameters.AddWithValue("@id", 1);
using var reader = command.ExecuteReader();
if (reader.Read())
{
var product = new Product
{
Id = (int)reader["Id"],
Name = (string)reader["Name"],
Price = (decimal)reader["Price"]
};
}
var product = await _context.Products.FindAsync(1);
ORMs bridge the gap between object-oriented programming and relational databases, allowing you to work with database data as C# objects.
Why Use an ORM?
Benefits
- Productivity: Write less code, focus on business logic
- Type safety: Compile-time checking instead of runtime errors
- Database agnostic: Switch databases with minimal code changes
- LINQ support: Query with C# instead of SQL
- Change tracking: Automatic detection of modified entities
- Migrations: Version control for database schema
- Relationships: Automatic handling of foreign keys
Drawbacks
- Performance overhead: Slightly slower than raw SQL
- Learning curve: Need to understand ORM concepts
- Complex queries: Some queries are harder to express
- Generated SQL: Less control over exact SQL
What is Entity Framework Core?
Entity Framework Core (EF Core) is Microsoft's modern, lightweight, cross-platform ORM for .NET.
Key Features
| Feature | Description |
|---|---|
| LINQ Queries | Query databases using C# LINQ syntax |
| Change Tracking | Automatically tracks entity changes |
| Migrations | Code-first database schema management |
| Relationships | One-to-one, one-to-many, many-to-many |
| Lazy Loading | Load related data on demand |
| Raw SQL | Execute raw SQL when needed |
EF Core vs ADO.NET
| Aspect | EF Core | ADO.NET |
|---|---|---|
| Code | Less code, more productive | More code, more control |
| Type Safety | Compile-time checking | Runtime errors |
| Performance | Good for most scenarios | Fastest possible |
| Learning Curve | Moderate | Steeper (SQL knowledge) |
| Maintenance | Easier to maintain | More manual work |
Database Providers
EF Core supports multiple databases through database providers:
| Database | Provider Package |
|---|---|
| SQL Server | Microsoft.EntityFrameworkCore.SqlServer |
| PostgreSQL | Npgsql.EntityFrameworkCore.PostgreSQL |
| MySQL | Pomelo.EntityFrameworkCore.MySql |
| SQLite | Microsoft.EntityFrameworkCore.Sqlite |
| In-Memory | Microsoft.EntityFrameworkCore.InMemory |
| Cosmos DB | Microsoft.EntityFrameworkCore.Cosmos |
Installation Example
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
When to Use EF Core
✅ Good Use Cases
- CRUD applications: Standard create/read/update/delete
- Line-of-business apps: Enterprise applications
- Rapid development: Prototypes and MVPs
- Domain-driven design: Rich domain models
- Code-first approach: Define schema in code
❌ Consider Alternatives When
- High performance critical: Microseconds matter
- Complex queries: Heavy reporting, analytics
- Stored procedures: Existing SP-heavy architecture
- Bulk operations: Millions of records at once
- Legacy databases: Complex existing schemas
Simple Example
public class Product
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public decimal Price { get; set; }
public int Quantity { get; set; }
}
public class InvenTrackDbContext : DbContext
{
public DbSet<Product> Products { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Server=.;Database=InvenTrack;Trusted_Connection=True;");
}
}
using var context = new InvenTrackDbContext();
// Create
var product = new Product { Name = "Laptop", Price = 999.99m, Quantity = 10 };
context.Products.Add(product);
await context.SaveChangesAsync();
// Read
var allProducts = await context.Products.ToListAsync();
// Update
product.Price = 899.99m;
await context.SaveChangesAsync();
// Delete
context.Products.Remove(product);
await context.SaveChangesAsync();
Key Takeaways
- ORM: Object-Relational Mapping bridges objects and databases
- EF Core: Microsoft's modern, cross-platform ORM
- Benefits: Productivity, type safety, LINQ support
- Trade-offs: Slight performance overhead vs convenience
- Database providers: Support for SQL Server, PostgreSQL, MySQL, etc.
- Use cases: Best for CRUD apps, rapid development, domain models
- DbContext: Central class for database operations
- Entities: C# classes that map to database tables
You now understand what an ORM is and why EF Core is useful! In the next section, we'll dive deeper into DbContext and Entities—how to define your database context and entity classes.