Entity Framework Core Basics

Lesson 8: Entity Framework Core Basics

In this lesson, you will learn about Entity Framework Core (EF Core), the main Object-Relational Mapper (ORM) for .NET applications.


🗄️ What is EF Core?

Entity Framework Core is a lightweight, cross-platform ORM that:

  • Maps C# classes to database tables.
  • Handles CRUD operations automatically.
  • Supports LINQ queries against your data.

It works with many databases like SQL Server, SQLite, PostgreSQL, and more.


🔧 Setting Up EF Core

To add EF Core, install the NuGet package:


dotnet add package Microsoft.EntityFrameworkCore.SqlServer

Then create a DbContext to manage your entities.


🏷️ Example Entity and DbContext

Here is an example model and context:


using Microsoft.EntityFrameworkCore;

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

public class AppDbContext : DbContext
{
    public DbSet Products { get; set; }

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


📝 Creating the Database

Use migrations to create and update the database schema:


dotnet ef migrations add InitialCreate
dotnet ef database update

This generates and applies SQL scripts automatically.


⚙️ Performing CRUD Operations

Example of adding a new record:


using (var context = new AppDbContext())
{
    var product = new Product { Name = "Book", Price = 9.99m };
    context.Products.Add(product);
    context.SaveChanges();
}

Example of querying data:


using (var context = new AppDbContext())
{
    var products = context.Products
                          .Where(p => p.Price > 5)
                          .ToList();

    foreach (var p in products)
    {
        Console.WriteLine($"{p.Name}: {p.Price}");
    }
}


🌟 Benefits of EF Core

EF Core provides:

  • Productivity through automatic migrations.
  • Strongly-typed LINQ queries.
  • Database-agnostic code.
  • Change tracking and concurrency handling.

📝 Summary

Entity Framework Core simplifies database access, making it easier to work with data using C# classes.


✅ Next Lesson

Lesson 9: Dependency Injection in .NET

تعليقات

المشاركات الشائعة من هذه المدونة

Entity Framework - ما هو ORM؟ ونبذة عن Dapper وNHibernate

1.1 SQL Introduction

Entity Framework - مقدمة عن Entity Framework