Entity Framework - potatoscript/csharp GitHub Wiki
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.
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! π‘β¨
Hereβs a step-by-step breakdown:
- π₯ Model Your Data β Create classes to represent your database tables.
- π₯ Set Up the Database Context β Define a bridge that connects your classes to the database.
- π₯ Perform CRUD Operations β Use simple C# commands to manage the data.
To use Entity Framework in your project, youβll need to install a package.
- Open Visual Studio.
- Open the Package Manager Console:
- Click on Tools β NuGet Package Manager β Package Manager Console.
- Run the following command:
Install-Package Microsoft.EntityFrameworkCore
- Also install the SQL Server provider:
Install-Package Microsoft.EntityFrameworkCore.SqlServer
- If you plan to generate migrations, install this:
Install-Package Microsoft.EntityFrameworkCore.Tools
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.
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.
The DbContext class is like a warehouse manager π’ who controls how data moves in and out of the warehouse.
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 thePotatoes
table in the database. -
OnConfiguring
β Configures the database connection using a connection string.
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. ποΈ
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.
Now that our Potato Warehouse is ready, we can start adding, reading, updating, and deleting data using C# commands!
To add a new potato to the warehouse:
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.
β
Potato added successfully!
To get all potatoes in the warehouse:
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.
π₯ Golden Potato (Yukon Gold) - 3.5 per kg
π₯ Sweet Potato (Beauregard) - 2.0 per kg
To update the price of a potato:
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.
β
Potato price updated successfully!
To remove a potato from the warehouse:
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.
β
Potato removed successfully!
You can use LINQ (Language Integrated Query) to filter and query data more efficiently. Itβs like asking very specific questions about your potatoes. π
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.
π 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 |