public async Task SeedAsync(BeverageContext context, IHostingEnvironment env, ILogger <BeverageContextSeed> logger) { var policy = this.CreatePolicy(logger, nameof(BeverageContextSeed)); await policy.ExecuteAsync(async() => { if (!context.Manufacturers.Any()) { await context.Manufacturers.AddRangeAsync(this.GetManufacturersFromFile(logger)); await context.SaveChangesAsync(); } if (!context.BeverageTypes.Any()) { await context.BeverageTypes.AddRangeAsync(this.GetBeverageTypesFromFile(logger)); await context.SaveChangesAsync(); } if (!context.BeverageStyles.Any()) { await context.BeverageStyles.AddRangeAsync(this.GetBeverageStylesFromFile(context, logger)); await context.SaveChangesAsync(); } if (!context.Beverages.Any()) { await context.Beverages.AddRangeAsync(this.GetBeveragesFromFile(context, logger)); await context.SaveChangesAsync(); } }); }
private IEnumerable <Beverage> GetBeveragesFromFile(BeverageContext context, ILogger <BeverageContextSeed> logger) { string csvFileBeverages = ResourceHelper.GetManifestResourceAsString($"{BeverageDataNameSpace}.Beverages.csv"); string[] csvheaders = null; try { string[] requiredHeaders = { "name", "description", "alcoholpercent", "volume", "url", "beveragestylename", "beveragetypename", "manufacturername" }; csvheaders = this.GetHeaders(csvFileBeverages, requiredHeaders); } catch (Exception ex) { logger.LogError(ex.Message); } var beverageTypeIdLookup = context.BeverageTypes.ToDictionary(ct => ct.Name, ct => ct.Id); var beverageStyleIdLookup = context.BeverageStyles.ToDictionary(ct => ct.Name, ct => ct.Id); var manufacturerIdLookup = context.Manufacturers.ToDictionary(ct => ct.Name, ct => ct.Id); return(csvFileBeverages.SplitCsvRows() .Skip(1) // skip header row .Select(row => Regex.Split(row, ColumnRegexPattern)) .SelectTry(column => this.CreateBeverage(column, csvheaders, beverageTypeIdLookup, beverageStyleIdLookup, manufacturerIdLookup, logger)) .OnCaughtException(ex => { logger.LogError(ex.Message); return null; }) .Where(x => x != null)); }