shopping-cart-blazor-wasm/Server/Data/Database.cs

46 lines
1.7 KiB
C#
Raw Permalink Normal View History

2020-06-19 10:20:16 +02:00
using Microsoft.EntityFrameworkCore;
using ShoppingCartStarter.Server.DomainModels;
namespace ShoppingCartStarter.Server.Data
{
public class Database
{
/// <summary>
/// Seed dummy cart data
/// </summary>
public static void InitialiseDatabase(IApplicationBuilder app, IWebHostEnvironment env)
{
using var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope();
using var context = serviceScope.ServiceProvider.GetRequiredService<StoreContext>();
context.Database.Migrate();
ShoppingCart cart;
if (context.Carts.Any())
{
cart = context.Carts
.Include(x=>x.LineItems)
.FirstOrDefault();
}
else
2020-06-19 10:20:16 +02:00
{
cart = new ShoppingCart();
context.Carts.Add(cart);
}
2020-06-19 10:20:16 +02:00
if (cart?.LineItems.Count == 0)
{
cart.LineItems.AddRange(new[]
2020-06-19 10:20:16 +02:00
{
new LineItem {Image = "test-image.jpg", Name = "Big T-shirt", Price = 39.50m, Quantity = 2},
new LineItem {Image = "test-image.jpg", Name = "Small White T-shirt", Price = 19.50m, Quantity = 1},
new LineItem {Image = "test-image.jpg", Name = "Smart Speaker", Price = 23.00m, Quantity = 1},
new LineItem {Image = "test-image.jpg", Name = "Dumb Speaker", Price = 99.00m, Quantity = 3},
2020-07-10 15:31:40 +02:00
new LineItem {Image = "test-image.jpg", Name = "Giraffe Poster", Price = 9.00m, Quantity = 4}
});
2020-06-19 10:20:16 +02:00
}
context.SaveChanges();
2020-06-19 10:20:16 +02:00
}
}
}