Join_DB_Table - lucyberryhub/WPF.Tutorial GitHub Wiki
Hey, cutie! πβ¨ Todayβs tutorial is all about joining tables in EF Core, but weβre doing it berry-cherry style! π₯§ Imagine combining a basket of juicy berries with a bowl of cherries to make the most delicious dessert ever! Letβs whip up some sweet code magic. ππ
Weβre going to learn how to:
- Join two tables dynamically using EF Core. ππ
- Select custom properties from the joined data (like picking the ripest fruit). πΈ
- Filter the data with a condition that fits your needs! πΌ
- Save the results into a JSON file for later berry-good use. π
Letβs break down this cute recipe!
The berry table contains sweet little berries with properties like:
- BerryId: A unique ID for each berry.
- BerryFlavor: The flavor profile of the berry.
- BerryName: The adorable name of the berry!
The cherry table contains the cherry toppings, with properties like:
- CherryId: A unique ID for each cherry.
- CherryType: The type of cherry.
- CherryName: The cute name of the cherry!
Letβs get our aprons on and bake this berry-cherry code pie! π₯§β¨
// π BerryModel (Table 1)
public class BerryModel
{
public string BerryId { get; set; } // Unique berry identifier
public string BerryFlavor { get; set; } // Flavor of the berry
public string BerryName { get; set; } // Name of the berry
}
// π CherryModel (Table 2)
public class CherryModel
{
public string CherryId { get; set; } // Unique cherry identifier
public string CherryType { get; set; } // Type of cherry
public string CherryName { get; set; } // Name of the cherry
}
// πΈ BerryCherryDbContext
public class BerryCherryDbContext : DbContext
{
public DbSet<BerryModel> Berries { get; set; } // π Table of berries
public DbSet<CherryModel> Cherries { get; set; } // π Table of cherries
// Method to dynamically fetch a DbSet
public DbSet<T> GetBerryCherrySet<T>() where T : class
{
return Set<T>();
}
}
using (var berryCherryContext = new BerryCherryDbContext())
{
// π Fetch the Berry DbSet
var berrySet = berryCherryContext.GetBerryCherrySet<BerryModel>();
// π Fetch the Cherry DbSet
var cherrySet = berryCherryContext.GetBerryCherrySet<CherryModel>();
// π₯§ Join the Berry-Cherry Tables
var berryCherryPie = await berrySet
.Join(cherrySet,
berry => berry.BerryId, // Match on BerryId
cherry => cherry.CherryId, // Match on CherryId
(berry, cherry) => new // Combine the results
{
BerryId = berry.BerryId,
BerryFlavor = berry.BerryFlavor,
BerryName = berry.BerryName,
CherryId = cherry.CherryId,
CherryType = cherry.CherryType,
CherryName = cherry.CherryName
})
.Where(pie => pie.BerryFlavor == "Sweet") // Filter for sweet berries π¬
.ToListAsync();
// π Save to a JSON File
if (berryCherryPie.Any())
{
await BerryJsonHelper.SaveBerryDataAsync("berry-cherry-pie.json", berryCherryPie);
}
else
{
MessageBox.Show("No berries or cherries found! ππ",
"Oh No!",
MessageBoxButton.OK,
MessageBoxImage.Information);
}
}
Hereβs the helper class to save your data in a super cute JSON file! πΎβ¨
public static class BerryJsonHelper
{
public static async Task SaveBerryDataAsync<T>(string filePath, T data)
{
var json = JsonConvert.SerializeObject(data, Formatting.Indented); // Pretty JSON π
await File.WriteAllTextAsync(filePath, json);
MessageBox.Show("Your berry-cherry pie has been saved! π₯§",
"Yay!",
MessageBoxButton.OK,
MessageBoxImage.Information);
}
}
-
Joined the Tables:
- The
berrySet
(Berries π) andcherrySet
(Cherries π) were joined using theirBerryId
andCherryId
.
- The
-
Selected Sweet Properties:
- We picked properties like
BerryName
andCherryType
for the result.
- We picked properties like
-
Filtered the Results:
- We applied a condition to only select berries with a
BerryFlavor
of"Sweet"
.
- We applied a condition to only select berries with a
-
Saved to JSON:
- We saved the yummy result to a JSON file named
berry-cherry-pie.json
for later use.
- We saved the yummy result to a JSON file named
Hereβs what your berry-cherry-pie.json
might look like:
[
{
"BerryId": "B001",
"BerryFlavor": "Sweet",
"BerryName": "Strawberry",
"CherryId": "C001",
"CherryType": "Red",
"CherryName": "Red Cherry"
},
{
"BerryId": "B002",
"BerryFlavor": "Sweet",
"BerryName": "Blueberry",
"CherryId": "C002",
"CherryType": "Black",
"CherryName": "Black Cherry"
}
]
Wasnβt that just the cutest way to join tables? ππ Remember, coding doesnβt have to be boringβadd a touch of sweetness, and itβll be berry fun! πΌ
Oh no, I got too serious for a moment! Letβs make this adorable and full of Lucy Berryβs sparkling charm! πΈπβ¨ Rewritten in cutie, girly Lucy Berry style, coming right up!
Hi, sweeties! π Itβs time to sprinkle some magic into your database journey with the ultimate LoadData
method! π This method is perfect for fetching, joining, and saving data like a pro! Get ready to level up your app with lots of berry-flavored charm! ππ
- Fetch a special ingredient: Grabs a specific value from your table where the ID is a juicy "2." π¬
- Berry-magic join: Combines two magical tables to create a sweet and delicious data result! πβ¨
- Save the cherries on top: Saves everything to a JSON file, ready to display in your app. πΎπ
- Berry-cute error handling: Even if something goes wrong, Lucy Berryβs got your back! π
Hereβs the cutie-pie code for the magical LoadData
method! Add it to your project and watch the magic happen! π
private async Task LoadData()
{
try
{
using (var berryCherryContext = new BerryCherryDbContext()) // πΈ Open a magical Berry Cherry database session π
{
// π Sweet Table #1 (Berry Pie)
var berryTable = berryCherryContext.GetBerrySet<EnvBerryPieModel>();
// π Sweet Table #2 (Cherry Tart)
var cherryTable = berryCherryContext.GetBerrySet<EnvCherryTartModel>();
// β¨ Fetch the special berry (Id = 2)! πΈ
var cherryTopping = await berryTable
.Where(b => EF.Property<string>(b, "BerryId") == "2") // π Select the juicy ID 2 π
.Select(b => b.BerrySweetnessText)
.FirstOrDefaultAsync();
// πβ¨ Perform a berry-cherry join! π
var magicalData = await berryTable
.Join(cherryTable,
berry => EF.Property<string>(berry, "BerryId"), // π₯§ Match BerryId π
cherry => EF.Property<string>(cherry, "CherryId"), // π Match CherryId π
(berry, cherry) => new // π Result Selector β¨
{
BerryDim1 = berry.BerrySmallText,
BerryDim2 = berry.BerryLargeText,
CherryTartExtra = cherry.CherrySpecialText,
BerryTartSecret = cherryTopping, // π From the previous fetch!
CherryDim1 = cherry.CherrySmallText,
CherryDim2 = cherry.CherryLargeText,
})
//.Where(item => item.BerryDim1 == "Extra Sweet") // Optional: Filter for the sweetest berries π
.ToListAsync();
// πΎ Save your magical data to a JSON file! β¨
if (magicalData.Any())
{
await JsonHelper.WriteToJsonFileAsync(viewModel.BerryCherryJsonFile, magicalData); // Save it! π
await viewModel.ReloadBerryCherryData(); // Reload the sweet data πΈβ¨
}
else
{
MessageBox.Show("Oh no! No sweet data found. π Try again later!",
"Oopsie Daisy! π",
MessageBoxButton.OK,
MessageBoxImage.Information);
}
}
}
catch (Exception berryOops)
{
MessageBox.Show($"Oopsie, something went wrong! πΈ Error: {berryOops.Message}",
"Uh-oh! π",
MessageBoxButton.OK,
MessageBoxImage.Error);
}
}
We use BerryCherryDbContext
to connect to our magical berry database! Itβs super easy to fetch data from your tables with this setup.
Look for the berry with Id = 2
(because every sweet recipe needs a hero!). This is done with:
var cherryTopping = await berryTable
.Where(b => EF.Property<string>(b, "BerryId") == "2")
.Select(b => b.BerrySweetnessText)
.FirstOrDefaultAsync();
Join EnvBerryPieModel
(berry table) and EnvCherryTartModel
(cherry table) using their magical IDs. Combine their properties into a berry-cherry result:
var magicalData = await berryTable
.Join(cherryTable,
berry => EF.Property<string>(berry, "BerryId"),
cherry => EF.Property<string>(cherry, "CherryId"),
(berry, cherry) => new
{
// Combine berry and cherry data π
BerryDim1 = berry.BerrySmallText,
BerryDim2 = berry.BerryLargeText,
CherryTartExtra = cherry.CherrySpecialText,
BerryTartSecret = cherryTopping,
CherryDim1 = cherry.CherrySmallText,
CherryDim2 = cherry.CherryLargeText,
})
.ToListAsync();
Write the combined berry-cherry data to a JSON file. Sweet and simple!
If something goes wrong, display a berry-cute error message to keep things friendly and fun! πΈ
Hereβs how you can call this adorable method in your app:
// Load all the berry-cherry magic β¨π
await LoadData();
MessageBox.Show("Yay! The sweet data is ready! π", "Berry Success! πΈ",
MessageBoxButton.OK, MessageBoxImage.Information);