Entity Framework - potatoscript/csharp GitHub Wiki

πŸ₯” Entity Framework (EF) in C# πŸ₯”


🎯 What Is Entity Framework (EF)?

Entity Framework (EF) is like a magic translator that helps your C# code talk to a database. Imagine you’re the potato boss πŸ₯”πŸ‘‘, and you give instructions in English, but the warehouse only understands SQL.

πŸ’‘ EF takes your C# commands and translates them into SQL so that the database understands them.


🍟 Why Use Entity Framework?

Using SQL is like giving detailed, step-by-step instructions to the warehouse, such as:

  • πŸ₯” β€œAdd a new potato to the inventory.”
  • πŸ₯” β€œCheck how many golden potatoes we have.”
  • πŸ₯” β€œUpdate the price of purple potatoes.”
  • πŸ₯” β€œRemove rotten potatoes from the warehouse.”

With Entity Framework, you don’t need to write all those instructions in SQL! You can give the same instructions directly in C#, and EF does the hard work for you! πŸ’‘βœ¨


πŸ₯” How EF Works?

Here’s a step-by-step breakdown:

  1. πŸ₯” Model Your Data – Create classes to represent your database tables.
  2. πŸ₯” Set Up the Database Context – Define a bridge that connects your classes to the database.
  3. πŸ₯” Perform CRUD Operations – Use simple C# commands to manage the data.

πŸ₯” Step 1: Installing Entity Framework

To use Entity Framework in your project, you’ll need to install a package.


🧠 Step-by-Step Instructions:

  1. Open Visual Studio.
  2. Open the Package Manager Console:
    • Click on Tools β†’ NuGet Package Manager β†’ Package Manager Console.
  3. Run the following command:
Install-Package Microsoft.EntityFrameworkCore
  1. Also install the SQL Server provider:
Install-Package Microsoft.EntityFrameworkCore.SqlServer
  1. If you plan to generate migrations, install this:
Install-Package Microsoft.EntityFrameworkCore.Tools

πŸ₯” Step 2: Creating the Data Model

The data model defines how the database looks. It’s like making a blueprint of your potato warehouse with different shelves for various types of potatoes.


🧠 Example: Potato.cs

public class Potato
{
    public int Id { get; set; }         // Unique ID
    public string Name { get; set; }    // Potato name
    public string Type { get; set; }    // Type of potato
    public double PricePerKg { get; set; }  // Price per kg
}

βœ… Explanation:

  • Id – Primary key that uniquely identifies a potato.
  • Name – The name of the potato.
  • Type – The variety or type of potato.
  • PricePerKg – Price of the potato per kilogram.

πŸ₯” Step 3: Creating the Database Context

The DbContext class is like a warehouse manager 🏒 who controls how data moves in and out of the warehouse.


🧠 Example: PotatoContext.cs

using Microsoft.EntityFrameworkCore;

public class PotatoContext : DbContext
{
    public DbSet<Potato> Potatoes { get; set; }  // Potatoes table

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        // Database connection string
        optionsBuilder.UseSqlServer(@"Server=localhost;Database=PotatoDB;User Id=sa;Password=potato123;");
    }
}

βœ… Explanation:

  • DbSet<Potato> – Represents the Potatoes table in the database.
  • OnConfiguring – Configures the database connection using a connection string.

πŸ₯” Step 4: Adding Migrations

To create the database using Entity Framework, we need to generate migrations. Think of it like giving the warehouse blueprint to the workers before building starts. πŸ—οΈ


🧠 Run These Commands:

Add-Migration InitialCreate

βœ… Explanation:

  • This generates a migration file that describes how to create the Potatoes table.
Update-Database

βœ… Explanation:

  • This applies the migration and creates the PotatoDB database.

πŸŽ‰ Step 5: CRUD Operations Using EF

Now that our Potato Warehouse is ready, we can start adding, reading, updating, and deleting data using C# commands!


πŸ₯” 1. INSERT – Add a New Potato

To add a new potato to the warehouse:


🧠 C# Code:

using System;

class Program
{
    static void Main()
    {
        using (var context = new PotatoContext())
        {
            var newPotato = new Potato
            {
                Name = "Golden Potato",
                Type = "Yukon Gold",
                PricePerKg = 3.5
            };

            context.Potatoes.Add(newPotato);
            context.SaveChanges();

            Console.WriteLine("βœ… Potato added successfully!");
        }
    }
}

βœ… Explanation:

  • context.Potatoes.Add(newPotato) – Adds the new potato.
  • context.SaveChanges() – Saves the changes to the database.

🎁 Output:

βœ… Potato added successfully!

πŸ₯” 2. SELECT – Get All Potatoes

To get all potatoes in the warehouse:


🧠 C# Code:

using System;
using System.Linq;

class Program
{
    static void Main()
    {
        using (var context = new PotatoContext())
        {
            var potatoes = context.Potatoes.ToList();

            foreach (var potato in potatoes)
            {
                Console.WriteLine($"πŸ₯” {potato.Name} ({potato.Type}) - {potato.PricePerKg} per kg");
            }
        }
    }
}

βœ… Explanation:

  • context.Potatoes.ToList() – Retrieves all the potatoes.

🎁 Output:

πŸ₯” Golden Potato (Yukon Gold) - 3.5 per kg
πŸ₯” Sweet Potato (Beauregard) - 2.0 per kg

πŸ₯” 3. UPDATE – Modify Potato Price

To update the price of a potato:


🧠 C# Code:

using System;
using System.Linq;

class Program
{
    static void Main()
    {
        using (var context = new PotatoContext())
        {
            var potato = context.Potatoes.FirstOrDefault(p => p.Name == "Golden Potato");

            if (potato != null)
            {
                potato.PricePerKg = 4.0;
                context.SaveChanges();
                Console.WriteLine("βœ… Potato price updated successfully!");
            }
            else
            {
                Console.WriteLine("⚠️ Potato not found.");
            }
        }
    }
}

βœ… Explanation:

  • context.Potatoes.FirstOrDefault() – Finds the potato by name.
  • context.SaveChanges() – Saves the updated data to the database.

🎁 Output:

βœ… Potato price updated successfully!

πŸ₯” 4. DELETE – Remove a Potato

To remove a potato from the warehouse:


🧠 C# Code:

using System;
using System.Linq;

class Program
{
    static void Main()
    {
        using (var context = new PotatoContext())
        {
            var potato = context.Potatoes.FirstOrDefault(p => p.Name == "Golden Potato");

            if (potato != null)
            {
                context.Potatoes.Remove(potato);
                context.SaveChanges();
                Console.WriteLine("βœ… Potato removed successfully!");
            }
            else
            {
                Console.WriteLine("⚠️ Potato not found.");
            }
        }
    }
}

βœ… Explanation:

  • context.Potatoes.Remove(potato) – Removes the potato from the database.

🎁 Output:

βœ… Potato removed successfully!

πŸŽ‰ Bonus: Query with LINQ in EF

You can use LINQ (Language Integrated Query) to filter and query data more efficiently. It’s like asking very specific questions about your potatoes. 🌟


🧠 Example: Get Only Potatoes with Price > 3.0

var expensivePotatoes = context.Potatoes.Where(p => p.PricePerKg > 3.0).ToList();

βœ… Explanation:

  • Where(p => p.PricePerKg > 3.0) – Filters potatoes that are more expensive than 3.0 per kg.

πŸ₯” Summary of Entity Framework in C#

🌟 Step πŸ“ Description
πŸ₯” Install EF Add EF to your project
πŸ₯” Create Models Define classes to represent database
πŸ₯” Setup Context Connect C# with the database
πŸ₯” Add Migrations Generate and apply migrations
πŸ₯” Perform CRUD Insert, Retrieve, Update, and Delete
⚠️ **GitHub.com Fallback** ⚠️