private static uint SeedDatabase(string shopName, string currency, ICollection <ProductJsonDto> products, ICollection <UserJsonDto> users, int[][] map) { uint count = 0; var optionsBuilder = new DbContextOptionsBuilder <ShopMateContext>() .UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=ShopMateContext;Trusted_Connection=True;"); using var db = new ShopMateContext(optionsBuilder.Options); db.Database.Migrate(); var store = new Store(shopName, currency) { Map = map }; db.Set <Store>().Add(store); var cart = new Cart { Active = true }; db.Set <Cart>().Add(cart); cart.Owner = store; var vat21 = new PriceModifier(PriceModifierCode.Vat, "", 0.21M, PriceModifierKind.Multiplicative); foreach (var userDto in users) { var user = new User(userDto.Name, userDto.Email, userDto.Phone, userDto.Password); db.Set <User>().Add(user); } foreach (var product in products) { if (InsertProduct(db, store, vat21, product)) { count++; } } db.SaveChanges(); return(count); }
private static bool InsertProduct(ShopMateContext db, Store vendor, PriceModifier modifier, ProductJsonDto entry) { Gtin14?barcode = null; if (!(entry.Barcode is null) && !Gtin14.TryFromStandardBarcode(entry.Barcode, out barcode)) { Console.WriteLine($"-- Skipping product with invalid barcode: {entry.ProductId} {entry.Name}"); return(false); } if (!(db.Set <Product>().Find(entry.ProductId) is null)) { Console.WriteLine($"-- Not modifying product already present: {entry.ProductId} {entry.Name}"); return(false); } var category = MakeCategory(db.Categories, entry.Category, entry.SuperCategory); categoriesCache.Add(category); if (!(category.Parent is null)) { categoriesCache.Add(category.Parent); } var product = new Product( barcode, entry.Name.LimitLength(120), entry.Weight, entry.Volume, entry.OriginCountry?.LimitLength(2), entry.Price, entry.Images, entry.AvailableStock, (uint)entry.TimesSold !) { Id = entry.ProductId, }; product.Categories.Add(category); product.Vendors.Add(vendor); if (entry.Brands != null) { foreach (var name in entry.Brands) { var brand = db.Brands.MatchingOrNew(brandsCache, new Brand(name.LimitLength(50), new List <string>(), null)); product.Brands.Add(brand); } } product.PriceModifiers.Add(modifier); modifier.Products.Add(product); foreach (var position in entry.Positions) { product.Positions.Add(new Position(position.Item1, position.Item2)); } db.Set <Product>().Add(product); return(true); }