ASP.NET Core Tutorialprovides basic and advanced concepts of C# for beginners and professionals.

Introduction to Entity Framework Core

Back to: ASP.NET Core Tutorial

Entity Framework Core (EF Core) is a modern, lightweight, and cross-platform Object-Relational Mapper (ORM) for .NET. It allows developers to work with databases using .NET objects, significantly reducing the amount of data access code.


🧩 What is an ORM?

An ORM maps objects in code to tables in a database. With EF Core, you write C# classes and it handles translating them to SQL for you.


⚙️ Key Features of EF Core

Feature Description
LINQ Queries Query your database using LINQ in C#.
Change Tracking Tracks changes to objects so updates can be made automatically.
Migrations Update the database schema through code-based versioning.
Cross-platform Works on Windows, Linux, and macOS.
Multiple Database Support SQL Server, SQLite, PostgreSQL, MySQL, and more.

🧱 EF Core Components

Component Description
DbContext Represents a session with the database.
DbSet<TEntity> Represents a table of entities in the database.
Entity Classes Represent rows in the table (POCOs – Plain Old CLR Objects).
Migrations Tool for evolving your database schema from code.

✅ Quick Start Example

1. Install EF Core Packages

bash
 
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
 

2. Create an Entity Class

csharp
 
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}
 

3. Create a DbContext

csharp
 
public class AppDbContext : DbContext
{
    public DbSet<Product> Products { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder options)
        => options.UseSqlServer("Your_Connection_String_Here");
}
 

4. Create and Apply Migrations

bash
 
dotnet ef migrations add InitialCreate
dotnet ef database update
 

5. Use EF Core in Code

csharp
 
using var context = new AppDbContext();
context.Products.Add(new Product { Name = "Notebook", Price = 5.99m });
context.SaveChanges();
 

📚 EF Core Use Cases

  • CRUD operations in ASP.NET Core apps

  • Data access for microservices

  • Prototyping or small database-driven applications


📝 Summary

  • EF Core maps .NET classes to database tables.

  • It simplifies querying and updating databases using LINQ and C#.

  • It's ideal for modern .NET applications with support for code-first development and migrations.

Scroll to Top