Entity Framework
Entity Framework (EF) is a modern object-relational mapper (ORM) for .NET that enables developers to work with relational data using domain-specific objects that conceptually map to relational database schemas. EF Core is the latest version of Entity Framework and is a cross-platform, extensible, and high-performance data access technology for .NET.
What is Entity Framework?
Entity Framework allows you to query a subset of data from a database and issue commands to update the data store, all within object-oriented paradigms. EF provides a layered abstraction over the ADO.NET data providers, allowing you to interact with your database using .NET objects instead of writing raw SQL queries.
Key Features
- Object-Relational Mapping (ORM): Maps database tables to C# classes and rows to objects.
- LINQ to Entities: Allows you to query your database using Language Integrated Query (LINQ).
- Change Tracking: Automatically tracks changes made to retrieved entities.
- Migrations: Manages database schema changes over time.
- Model First, Database First, Code First: Supports different approaches to defining your data model.
- Performance Optimizations: Designed for high performance and efficiency.
Getting Started with EF Core
To start using EF Core, you'll typically:
- Install the EF Core NuGet Packages: Add the necessary packages to your project (e.g.,
Microsoft.EntityFrameworkCore
,Microsoft.EntityFrameworkCore.SqlServer
). - Define Your Model: Create C# classes to represent your database entities.
- Create a
DbContext
: A class that inherits fromDbContext
and represents a session with the database. - Configure the Database Connection: Specify the connection string to your database.
- Use LINQ to Query Data: Write LINQ queries against your
DbSet
properties in theDbContext
. - Save Changes: Use the
DbContext.SaveChanges()
method to persist changes to the database.
Example: Code First Approach
Here's a simple example using the Code First approach:
Entity Class:
public class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
DbContext:
using Microsoft.EntityFrameworkCore;
public class ApplicationDbContext : DbContext
{
public DbSet Products { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
// Replace with your actual connection string
optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;");
}
}
Usage:
using (var context = new ApplicationDbContext())
{
// Add a new product
var newProduct = new Product { Name = "Laptop", Price = 1200.50m };
context.Products.Add(newProduct);
context.SaveChanges();
// Query products
var allProducts = context.Products.ToList();
foreach (var product in allProducts)
{
Console.WriteLine($"- {product.Name}: ${product.Price}");
}
}