// [TestMethod] public void PopulateMovieGenresTableData() { TextReader readFile = new StreamReader(@"C:\Users\Abhil\Desktop\movies_metadata.csv"); var csv = new CsvReader(readFile); csv.Configuration.BadDataFound = null; csv.Configuration.ReadingExceptionOccurred = null; var moviesFromCsv = csv.GetRecords <dynamic>(); List <Movie> moviesFromDb; List <Genre> genresFromDb; Dictionary <int, List <Genre> > moviesGenresDictionary = new Dictionary <int, List <Genre> >(); foreach (var mov in moviesFromCsv) { List <Genre> genresTotal = new List <Genre>(); JArray genreArray = JArray.Parse(mov.genres); int id; var externalId = Int32.TryParse(mov.id, out id) ? id : 0; foreach (var g in genreArray) { var genres = JsonConvert.DeserializeObject <Genre>(g.ToString()); genresTotal.Add(genres); } moviesGenresDictionary.Add(externalId, genresTotal); } Database.SetInitializer <MovieDbContext>(null); using (var db = new MovieDbContext()) { moviesFromDb = db.Movies.ToList(); genresFromDb = db.Genres.ToList(); } using (var db = new MovieDbContext()) { // db.Configuration.AutoDetectChangesEnabled = false; foreach (var m in moviesFromDb) { var generesToAdd = moviesGenresDictionary[m.ExternalId]; Movie movie = new Movie() { Id = m.Id }; foreach (var g in generesToAdd) { int genreId = genresFromDb.Where(gn => gn.Name == g.Name).Select(gn => gn.Id).FirstOrDefault(); Genre genre = new Genre() { Id = genreId }; db.Database.ExecuteSqlCommand("Insert into MovieGenres Values({0},{1})", genreId, movie.Id); } } } }
// [TestMethod] public void PopulateGeneresLookupTableData() { TextReader readFile = new StreamReader(@"C:\Users\Abhil\Desktop\movies_metadata.csv"); var csv = new CsvReader(readFile); csv.Configuration.BadDataFound = null; csv.Configuration.ReadingExceptionOccurred = null; var moviesFromCsv = csv.GetRecords <dynamic>(); List <Genre> genresTotal = new List <Genre>(); foreach (var mov in moviesFromCsv) { JArray genreArray = JArray.Parse(mov.genres); int id; var ImdbId = Int32.TryParse(mov.id, out id) ? id : 0; foreach (var g in genreArray) { var genres = JsonConvert.DeserializeObject <Genre>(g.ToString()); genresTotal.Add(genres); } } List <Genre> genresDistinct = new List <Genre>(); foreach (var genre in genresTotal.Select(g => new { id = g.Id, name = g.Name }).Distinct()) { genresDistinct.Add(new Genre() { Id = genre.id, Name = genre.name }); } using (var scope = new TransactionScope()) { Database.SetInitializer <MovieDbContext>(null); using (var db = new MovieDbContext()) { db.Configuration.AutoDetectChangesEnabled = false; foreach (var g in genresDistinct) { var gg = new Genre { Id = g.Id, Name = g.Name }; db.Genres.Add(gg); } db.SaveChanges(); } scope.Complete(); } }