Entity Framework (EF) is an Object-Relational Mapper (ORM) that enables .NET developers to work with a database using .NET objects. It eliminates the need for most of the data-access code that developers usually need to write. Entity Framework Core (EF Core) is the modern version of Entity Framework and is designed to be lightweight, extensible, and cross-platform.
Why Do We Need Entity Framework?
- Productivity: EF reduces the amount of boilerplate code for database operations. Developers can focus more on business logic rather than the data access layer.
- Abstraction: EF abstracts the database schema, enabling developers to work with databases without having to write complex SQL queries.
- Maintainability: With EF, data access logic is centralized, making the application easier to maintain and refactor.
- Migration Support: EF supports database migrations, making it easier to evolve the database schema over time in a controlled manner.
Why It's Named "Entity Framework Core"?
EF Core is the redesigned version of EF, built to be more modular, lightweight, and flexible. The "Core" in its name signifies its foundation on .NET Core, enabling it to run on multiple platforms (Windows, Linux, macOS) and making it suitable for cloud applications.
Key Features of Entity Framework Core
- Cross-Platform: Runs on .NET Core, making it usable on different operating systems.
- Modular and Lightweight: Provides only the necessary components for ORM and can be extended with additional features as needed.
- LINQ Support: Allows querying databases using LINQ (Language Integrated Query).
- Migrations: Supports code-first migrations to evolve the database schema.
- Change Tracking: Automatically keeps track of changes to entities and manages updates to the database.
Implementation in C#
Setting Up Entity Framework Core.
Install EF Core NuGet Packages
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
Create a DbContext
using Microsoft.EntityFrameworkCore;
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Customer> Customers { get; set; }
public DbSet<Order> Orders { get; set; }
}
public class Customer
{
public int CustomerId { get; set; }
public string Name { get; set; }
public List<Order> Orders { get; set; }
}
public class Order
{
public int OrderId { get; set; }
public string ProductName { get; set; }
public int Quantity { get; set; }
public int CustomerId { get; set; }
public Customer Customer { get; set; }
}
Configure DbContext in Startup.cs
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
}
AppSettings Configuration
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
CRUD Operations with Entity Framework Core
Create Operation
public async Task AddCustomerAsync(Customer customer)
{
using (var context = new ApplicationDbContext(_options))
{
context.Customers.Add(customer);
await context.SaveChangesAsync();
}
}
Read Operation
public async Task<Customer> GetCustomerAsync(int customerId)
{
using (var context = new ApplicationDbContext(_options))
{
return await context.Customers.Include(c => c.Orders)
.FirstOrDefaultAsync(c => c.CustomerId == customerId);
}
}
Update Operation
public async Task UpdateCustomerAsync(Customer customer)
{
using (var context = new ApplicationDbContext(_options))
{
context.Customers.Update(customer);
await context.SaveChangesAsync();
}
}
Delete Operation
public async Task DeleteCustomerAsync(int customerId)
{
using (var context = new ApplicationDbContext(_options))
{
var customer = await context.Customers.FindAsync(customerId);
if (customer != null)
{
context.Customers.Remove(customer);
await context.SaveChangesAsync();
}
}
}
Conclusion
Entity Framework and Entity Framework Core simplify database operations, making them more intuitive and maintainable for developers. By using EF Core, developers can leverage the power of ORM to build efficient, scalable, and cross-platform applications with ease.