public async Task <bool> AddProducts(IFormFile formFile) { try { List <string> categoryNames = new List <string>(); List <string> colorCodeNames = new List <string>(); List <string> colorNames = new List <string>(); List <Product> products = new List <Product>(); var result = new StringBuilder(); using (var reader = new StreamReader(formFile.OpenReadStream())) { //Initially Skip first Line which cntain header reader.ReadLine(); //Read all lines in CSV file, Line by line reading will not even consume more memory while (reader.Peek() >= 0) { var lineValues = (await reader.ReadLineAsync()).Split(','); ExtractProduct(lineValues, ref colorCodeNames, ref categoryNames, ref colorNames, ref products); } } //Add All colorCodeNames List <ColorCode> colorCodes = colorCodeNames.Distinct().Select(x => new ColorCode { Code = x }).ToList(); _colorCodeRepository.AddList(colorCodes); //Add All categoryNames List <Category> categories = categoryNames.Distinct().Select(x => new Category { Name = x }).ToList(); _categoryRepository.AddList(categories); //Add All Colors List <Color> colors = colorNames.Distinct().Select(x => new Color { Name = x }).ToList(); _colorRepository.AddList(colors); _productContext.SaveChanges(); //Add All Artikels List <Artikel> artikels = products.Select(x => new Artikel { Key = x.Key, ArtikelCode = x.ArtikelCode, ColorCodeId = colorCodes.FirstOrDefault(y => y.Code == x.ColorCode).Id, Description = x.Description, Price = x.Price, DiscountPrice = x.DiscountPrice, DeliveredIn = x.DeliveredIn, CategoryId = categories.FirstOrDefault(y => y.Name == x.Q1).Id, Size = x.Size, ColorId = colors.FirstOrDefault(y => y.Name == x.Color).Id }).ToList(); _artikelRepository.AddList(artikels); return(true); } catch (Exception ex) { throw ex; } }