Skip to content

Instantly share code, notes, and snippets.

@carloswm85
Created March 4, 2023 14:28
Show Gist options
  • Select an option

  • Save carloswm85/dad08390a8201008c1ba5e043ca69cb0 to your computer and use it in GitHub Desktop.

Select an option

Save carloswm85/dad08390a8201008c1ba5e043ca69cb0 to your computer and use it in GitHub Desktop.
Seed data to database with Bogus.
using MegaDeskRazorPages.Data;
using Microsoft.EntityFrameworkCore;
using MegaDeskRazorPages.Models;
using MegaDeskRazorPages.Utilities;
using Bogus;
namespace MyScriptureJournal.Models;
public static class SeedData
{
public static Random Random = new Random();
public static Array DesktopMaterialValues = Enum.GetValues(typeof(DesktopMaterial));
public static int[] DeliveryDays = new[] { 3, 5, 7, 14 };
public static Faker faker = new Faker();
public static List<List<int>> shippingPrices = new()
{
new() { 60, 70, 80 },
new() { 40, 50, 60 },
new() { 30, 35, 40 }
};
public static void Initialize(IServiceProvider serviceProvider)
{
using (var context = new MegaDeskRazorPagesContext(
serviceProvider.GetRequiredService<
DbContextOptions<MegaDeskRazorPagesContext>>()))
{
if (context == null || context.DeskQuote == null)
{
throw new ArgumentNullException("Null MegaDeskRazorPagesContext");
}
// Look for any desk quotes.
if (context.DeskQuote.Any())
{
return; // DB has been already seeded
}
DeskQuote[] deskQuotes = GetDeskQuotesArray(quantity: 531, context: context);
context.DeskQuote.AddRange(deskQuotes);
context.SaveChanges();
}
}
private static DeskQuote[] GetDeskQuotesArray(int quantity, MegaDeskRazorPagesContext context)
{
DeskQuote[] arr = new DeskQuote[quantity];
for (int i = 0; i < arr.Length; i++)
{
Desk desk = GetSeededDesk(context);
int newDaysUntilDelivery = GetRandomDeliveryDay();
string newFullName = faker.Name.FullName();
DateTime newDate = GetRandomDay();
DeskQuote deskQuote = new DeskQuote
{
DeskId = desk.Id,
DaysUntilDelivery = newDaysUntilDelivery,
CustomerName = newFullName,
Date = newDate,
TotalCost = Calculator.CalculateTotalCost(desk, newDaysUntilDelivery)
};
arr[i] = deskQuote;
}
return arr;
}
private static int GetRandomDeliveryDay()
{
int index = Random.Next(0, DeliveryDays.Length);
return DeliveryDays[index];
}
private static DateTime GetRandomDay()
{
DateTime start = new DateTime(1995, 1, 1);
int range = (DateTime.Today - start).Days;
return start.AddDays(Random.Next(range));
}
private static Desk GetSeededDesk(MegaDeskRazorPagesContext context)
{
Array desktopMaterialValues = Enum.GetValues(typeof(DesktopMaterial));
var desk = new Desk
{
Width = Random.Next(24, 96),
Depth = Random.Next(12, 48),
NumDrawers = Random.Next(0, 7),
Material = (DesktopMaterial)desktopMaterialValues
.GetValue(Random
.Next(desktopMaterialValues.Length))
};
context.Desks.Add(desk);
context.SaveChanges();
return desk;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment