public override void Execute() { this.Data = new PetStoreEntities(); var countriesIds = this.Data .Countries .OrderBy(x => Guid.NewGuid()) .Select(x => x.Id) .ToList(); var randomSpeciesName = this.GenerateSomeRandomeStrings(5, 50, 400).ToList(); var countryIndex = 0; for (int i = 0; i < MaxNumberOfSpecies; i++) { if (countryIndex == 20) { countryIndex = 0; } var specie = new Species() { Name = randomSpeciesName[i], CountryId = countriesIds[countryIndex] }; this.Data.Species.Add(specie); // print . if (i % 10 == 0) { Console.Write("."); } // save dispose if (i % 20 == 0) { this.Data.SaveChanges(); this.Data.Dispose(); this.Data = new PetStoreEntities(); } countryIndex++; } this.Data.SaveChanges(); }
public static void ImportSpecies(int count) { Console.WriteLine("ImportSpecies"); var data = new PetStoreEntities(); var coutriesIds = data.Countries.Select(c => c.Id).ToList(); var countriesCount = coutriesIds.Count; // generate 100 ids list var countriesRandomCountryIds = new List<int>(); // add the unique 20 countriesRandomCountryIds.AddRange(coutriesIds); // add the rest to count for (int i = 0; i < count - countriesCount; i++) { var randomCountryIndex = RandomInstance.Next(0, countriesCount); var randomId = coutriesIds[randomCountryIndex]; countriesRandomCountryIds.Add(randomId); } // randomize var shuffledCountryIds = countriesRandomCountryIds.OrderBy(g => Guid.NewGuid()).ToList(); var speciesNames = new HashSet<string>(); do { speciesNames.Add(RandomGenerator.RandomString(5, 50)); } while (speciesNames.Count < count); var counter = 0; foreach (var specie in speciesNames) { var id = shuffledCountryIds[0]; shuffledCountryIds.RemoveAt(0); var newSpecie = new Species() { Name = specie, CountryId = id }; data.Species.Add(newSpecie); counter++; if (counter % 100 == 0) { data.SaveChanges(); data.Dispose(); data = new PetStoreEntities(); Console.Write("."); } } data.SaveChanges(); data.Dispose(); }