Instantly share code, notes, and snippets.

Embed
What would you like to do?
using Microsoft.EntityFrameworkCore;
using System.Threading;
using System.Threading.Tasks;
using MySample.Entities;
using SSW.DataOnion.Interfaces;
namespace MySample.Data.SampleData
{
public class SampleDataSeeder : IDataSeeder
{
public void Seed<TDbContext>(TDbContext dbContext) where TDbContext : DbContext
{
this.PopulateData(dbContext);
dbContext.SaveChanges();
}
public async Task SeedAsync<TDbContext>(TDbContext dbContext, CancellationToken cancellationToken = new CancellationToken()) where TDbContext : DbContext
{
this.PopulateData(dbContext);
await dbContext.SaveChangesAsync(cancellationToken);
}
private void PopulateData<TDbContext>(TDbContext dbContext) where TDbContext : DbContext
{
var category1 = new ProductCategory {Name = "TVs"};
var category2 = new ProductCategory { Name = "Microwaves" };
var category3 = new ProductCategory { Name = "Fridges" };
var product1 = new Product { Category = category1, Name = "42 inch Plazma TV", Sku = "42P" };
var product2 = new Product { Category = category1, Name = "55 inch LED TV", Sku = "55LED" };
var product3 = new Product { Category = category3, Name = "Small bar fridge", Sku = "SBF" };
var product4 = new Product { Category = category3, Name = "Medium Fridge", Sku = "MF" };
var product5 = new Product { Category = category3, Name = "Large French Door Fridge", Sku = "FDF" };
dbContext.Set<ProductCategory>().AddOrUpdate(category1);
dbContext.Set<ProductCategory>().AddOrUpdate(category2);
dbContext.Set<ProductCategory>().AddOrUpdate(category3);
dbContext.Set<Product>().AddOrUpdate(product1);
dbContext.Set<Product>().AddOrUpdate(product2);
dbContext.Set<Product>().AddOrUpdate(product3);
dbContext.Set<Product>().AddOrUpdate(product4);
dbContext.Set<Product>().AddOrUpdate(product5);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment