Entity Framework Core (EF Core) is a modern, lightweight, and extensible version of the Entity Framework, which is an Object-Relational Mapper (ORM) for .NET applications. It allows developers to work with databases using .NET objects, eliminating the need for most of the data-access code that developers usually need to write. Below, we will explore the key concepts of EF Core, including the Code-First approach, DbContext and DbSet, migrations, the repository pattern and unit of work, and LINQ queries with async operations.
What is Entity Framework Core?
Entity Framework Core (EF Core) is a modern, lightweight, open-source Object-Relational Mapper (ORM) for .NET. It allows developers to interact with databases using C# objects, eliminating the need to write most raw SQL queries.
🧠Think of EF Core as a bridge between your C# code and the SQL database.
Key Features of EF Core
- Cross-platform: Works on Windows, Linux, macOS
- LINQ support: Query databases using C# syntax
- Change tracking: Tracks changes in objects to update the DB
- Migrations: Manage schema changes via code
- Lazy/Eager/Explicit Loading: Controls how related data is loaded
- Concurrency Handling: Manages data conflicts in multi-user apps
- Database First Approach.
- Code First Approach.
What is the Code-First Approach?
How Code-First Works:
Step-by-Step Example of Code-First Approach.
dotnet add package Microsoft.EntityFrameworkCore dotnet add package Microsoft.EntityFrameworkCore.SqlServer dotnet add package Microsoft.EntityFrameworkCore.Tools
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; public class Product { [Key] // Defines primary key public int Id { get; set; } [Required] // NOT NULL [MaxLength(100)] // Max length for Name public string Name { get; set; } [Column(TypeName = "decimal(10,2)")] // Define precision for Price [Range(0, 99999.99)] // Validation range public decimal Price { get; set; } [Required] [DefaultValue(true)] // Default value public bool IsAvailable { get; set; } = true; }
public class AppDbContext : DbContext { public DbSet<Product> Products { get; set; } public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { } }
- Configure the connection to the database
- Map your C# models (like Product) to database tables
- Track changes and execute queries
- Save data to the database
builder.Services.AddDbContext<AppDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
"ConnectionStrings": { "DefaultConnection": "Server=.;Database=EFCoreDemo;Trusted_Connection=True;" }
dotnet ef migrations add InitialCreate dotnet ef database update
- Create a Migrations folder
- Generate SQL commands
- Apply them to your database
public class ProductService { private readonly AppDbContext _context; public ProductService(AppDbContext context) { _context = context; } public async Task AddProduct() { var product = new Product { Name = "Laptop", Price = 1500 }; _context.Products.Add(product); await _context.SaveChangesAsync(); } }
What is the Database-First Approach?
When to Use It?
- You already have a pre-existing database
- You're working with legacy systems
- You want your C# models to match a database that someone else designed
Step-by-Step Example of Database-First Approach:
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
dotnet ef dbcontext scaffold "Your_Connection_String" Microsoft.EntityFrameworkCore.SqlServer -o Models
- "Your_Connection_String" – The connection string to your existing DB
- Microsoft.EntityFrameworkCore.SqlServer – The database provider
- -o Models – Output directory for generated models and DbContext
- DbContext file → manages the connection to the DB
- Model classes for each table → mapped to DB tables
What is the Repository Pattern?
- Encapsulates data access logic
- Promotes loose coupling
- Makes unit testing easier
- Clean separation of concerns
No comments:
Post a Comment