Skip to content

Entity Framework Core: Real‐World Flow Explanation Using a Digital Wallet

Sann Lynn Htun edited this page Nov 22, 2024 · 1 revision

Entity Framework Core (EF Core)

EF Core is an open-source, lightweight, and extensible Object-Relational Mapping (ORM) framework for .NET. It simplifies database interactions by allowing developers to work with databases using .NET objects, eliminating the need to write complex SQL queries.

Why Should You Use EF Core?

  1. Productivity:

    • Automates repetitive database tasks like generating queries, managing connections, and handling data updates.
    • Developers can focus on business logic instead of database infrastructure.
  2. Database Independence:

    • Supports multiple database providers, including SQL Server, SQLite, PostgreSQL, and more.
    • Enables switching databases with minimal code changes.
  3. Simplified Maintenance:

    • Provides a single place to define and update database schema (DbContext).
    • Tracks and updates database changes using migrations.
  4. Seamless Integration:

    • Integrates naturally with .NET applications and technologies like ASP.NET Core, Blazor, and more.
  5. Strongly-Typed Queries:

    • Supports LINQ (Language Integrated Query) for querying data, reducing runtime errors by validating queries at compile time.

Advantages of EF Core

Advantage Description
Ease of Use Simplifies database operations by allowing developers to use C# code instead of SQL.
Cross-Platform Works across Windows, Linux, and macOS in .NET Core applications.
Entity Tracking Tracks changes to objects and automatically applies updates to the database.
Migrations Provides tools to manage and version control database schema changes.
Relationships Handling Easily defines and manages relationships (e.g., one-to-many, many-to-many).
Performance Optimizations Supports features like lazy loading, eager loading, and batching queries for performance.

Entity Framework Core: Real-World Flow Explanation Using a Digital Wallet

Let’s explain Entity Framework Core (EF Core) concepts like TransactionDto, AppDbContext, OnConfiguring, and CRUD operations with the analogy of managing a Digital Wallet.


Scenario: Managing a Digital Wallet

In this analogy:

  1. Transactions are the data model (DTO), representing money transfers in the wallet.
  2. The wallet database stores all transaction records.
  3. Digital Wallet Service acts as the EF Core DbContext, handling communication with the database.
  4. CRUD operations represent adding, viewing, updating, or deleting transactions.

Step-by-Step Explanation

1. Data Model (DTO): Representing Transactions

In EF Core, a DTO (Data Transfer Object) defines the structure of data in your application.

  • A TransactionDto represents individual wallet transactions, including transaction ID, amount, type (debit/credit), and timestamp.

Code Example: TransactionDto

public class TransactionDto
{
    public int Id { get; set; }           // Unique identifier for each transaction
    public decimal Amount { get; set; }  // Transaction amount
    public string Type { get; set; }     // Debit or Credit
    public DateTime Timestamp { get; set; } // Transaction date and time
}
  • Analogy: Each transaction record is like an entry in your wallet statement, detailing when and how much money was credited or debited.

2. DbContext: Acting as the Wallet Service

The DbContext acts as the service managing wallet transactions:

  • It knows how to connect to the database and manage transaction records.
  • It maps your TransactionDto to a database table and provides methods for CRUD operations.

Code Example: AppDbContext

public class AppDbContext : DbContext
{
    public DbSet<TransactionDto> Transactions { get; set; } // Represents the "Transactions" table

    // Configuring the database connection
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("Server=.;Database=DigitalWalletDb;Trusted_Connection=True;");
    }
}
  • Analogy: The wallet service connects to the database to record or retrieve transactions.

3. OnConfiguring: Setting Up the Wallet Database

The OnConfiguring method sets up the connection string, specifying where the wallet's transaction records (database) are stored.

  • Real-World Analogy: Just like a wallet service connects to the cloud server to fetch your transaction history, EF Core connects to the database using the connection string.

4. CRUD Operations: Managing Transactions

CRUD operations let you manage wallet transactions through EF Core:

Operation EF Core Term Wallet Action
Create Add method Add a new transaction record.
Read ToList or Find View transaction history.
Update Update method Modify transaction details.
Delete Remove method Delete a transaction record.

Code Examples for CRUD Operations

1. Create (Add a New Transaction)

Add a new transaction to the wallet.

using (var context = new AppDbContext())
{
    var newTransaction = new TransactionDto
    {
        Amount = 100.00m,
        Type = "Credit",
        Timestamp = DateTime.Now
    };
    context.Transactions.Add(newTransaction); // Add a new transaction
    context.SaveChanges(); // Save changes to the database
}
  • Real-World Analogy: A customer adds funds to their wallet, and the service records the transaction as a credit.

2. Read (View Transaction History)

Retrieve the entire transaction history from the wallet.

using (var context = new AppDbContext())
{
    var transactions = context.Transactions.ToList(); // Fetch all transactions
    foreach (var transaction in transactions)
    {
        Console.WriteLine($"Type: {transaction.Type}, Amount: {transaction.Amount}, Timestamp: {transaction.Timestamp}");
    }
}
  • Real-World Analogy: A user views the transaction history in their wallet app.

3. Update (Modify a Transaction)

Update details of an existing transaction.

using (var context = new AppDbContext())
{
    var transaction = context.Transactions.FirstOrDefault(t => t.Id == 1); // Find transaction with ID 1
    if (transaction != null)
    {
        transaction.Amount = 150.00m; // Update the amount
        context.Transactions.Update(transaction); // Mark for update
        context.SaveChanges(); // Save changes to the database
    }
}
  • Real-World Analogy: The wallet service updates the transaction record (e.g., correcting an amount).

4. Delete (Remove a Transaction)

Remove a transaction from the wallet's database.

using (var context = new AppDbContext())
{
    var transaction = context.Transactions.FirstOrDefault(t => t.Id == 1); // Find transaction with ID 1
    if (transaction != null)
    {
        context.Transactions.Remove(transaction); // Remove the transaction
        context.SaveChanges(); // Save changes to the database
    }
}
  • Real-World Analogy: The wallet service deletes an incorrect or canceled transaction from the record.

Flow Summary: How It Works Together

  1. Define the Model: TransactionDto represents the structure of a transaction in the wallet.
  2. DbContext: AppDbContext acts as the wallet service connecting the app to the transaction database.
  3. OnConfiguring: Configures the database connection for storing and retrieving transactions.
  4. CRUD Operations: Provide functionality to add funds, view history, update transaction details, and delete records.

This analogy simplifies understanding of EF Core by mapping its concepts to how a digital wallet manages transactions in real life!

C# Basics Wiki

Core Concepts

Object-Oriented Programming (OOP)

Advanced Topics

Miscellaneous

Tools and Resources

Clone this wiki locally