Entity Framework (EF) is an Object-Relational Mapping (ORM) framework for .NET applications. It simplifies data access by allowing developers to work with databases using C# objects, rather than writing SQL queries directly. This abstraction makes it easier to focus on the business logic of the application without needing to worry too much about the database structure.
Key Features of Entity Framework
1. Code-First, Database-First, and Model-First Approaches:
- Code-First: You define your models in C# code, and EF generates the database schema.
- Database-First: You start with an existing database, and EF generates the model classes.
- Model-First: You design your model in a visual designer, and EF generates the database schema and classes.
2. LINQ to Entities:
- Use LINQ (Language Integrated Query) to perform queries on the database using C# syntax.
3. Change Tracking:
- EF automatically tracks changes made to objects so it knows what to update in the database.
4. Lazy Loading:
- Related data is automatically loaded from the database when accessed for the first time.
5. Migration Support:
- EF supports database migrations, which allow you to update the database schema over time as your application evolves.
How Entity Framework Works
1. Define Your Models: These are simple C# classes that represent the tables in your database.
Code:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
2. Set Up the DbContext: The DbContext is a class that manages the connection to the database and provides methods for querying and saving data.
Code:
public class AppDbContext : DbContext
{
public DbSet Products { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(“YourConnectionStringHere”);
}
}
3. Perform Database Operations:
Insert data:
using (var context = new AppDbContext())
{
var product = new Product { Name = "Laptop", Price = 999.99m };
context.Products.Add(product);
context.SaveChanges();
}
4. Retrieve data:
using (var context = new AppDbContext())
{
var products = context.Products.ToList();
}
5. Update data:
using (var context = new AppDbContext())
{
var product = context.Products.FirstOrDefault(p => p.Id == 1);
if (product != null)
{
product.Price = 899.99m;
context.SaveChanges();
}
}
6. Delete data:
using (var context = new AppDbContext())
{
var product = context.Products.FirstOrDefault(p => p.Id == 1);
if (product != null)
{
context.Products.Remove(product);
context.SaveChanges();
}
}