# Entity Framework Core Deep Dive in ASP.NET Core

Now that we can build APIs, it's time to hook them up to a database using **Entity Framework Core (EF Core)**, the official ORM (Object-Relational Mapper) for .NET.

In this post, we'll dive into how to use EF Core with ASP.NET Core to persist, query, and manage data cleanly.

---

## 🧱 Step 1: Install EF Core Packages

If you're using SQL Server:

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

If you're using another DB (e.g., PostgreSQL), use the relevant provider.

---

## 🗃️ Step 2: Create Your DbContext

```csharp
public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) {}

    public DbSet<Product> Products { get; set; }
}
```

Add your model if you haven't already:

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

---

## ⚙️ Step 3: Configure in Program.cs

```csharp
builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
```

In `appsettings.json`:

```json
"ConnectionStrings": {
  "DefaultConnection": "Server=localhost;Database=MyDb;Trusted_Connection=True;"
}
```

---

## 🛠️ Step 4: Add Migrations & Update DB

```bash
dotnet ef migrations add InitialCreate
dotnet ef database update
```

EF will scaffold the database based on your models and context.

---

## 📦 CRUD with EF Core

In your controller or service, inject `AppDbContext`:

```csharp
private readonly AppDbContext _context;

public ProductsController(AppDbContext context)
{
    _context = context;
}

[HttpGet]
public async Task<IActionResult> GetAll() =>
    Ok(await _context.Products.ToListAsync());

[HttpPost]
public async Task<IActionResult> Create(Product product)
{
    _context.Products.Add(product);
    await _context.SaveChangesAsync();
    return CreatedAtAction(nameof(GetAll), new { id = product.Id }, product);
}
```

---

## 🔗 Relationships Example

```csharp
public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }

    public ICollection<Product> Products { get; set; }
}

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

    public Category Category { get; set; }
}
```

EF handles foreign keys and joins for you. Just use `.Include()` when querying:

```csharp
_context.Products.Include(p => p.Category).ToList();
```

---

## 🧪 Bonus: Seeding Data

Inside your `DbContext`:

```csharp
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Product>().HasData(
        new Product { Id = 1, Name = "Sample", Price = 9.99M }
    );
}
```

---

## ✅ Up Next

We’ve got data flowing! Now let’s secure it.

Next: **Authentication & Authorization with JWT** — protecting your APIs the modern way.

➡️ [Authentication & Authorization with JWT →](./aspnetcore-jwt-auth)

