I have 5 entities:
public class Album
{
public int Id { get; set; }
public string Title { get; set; }
public virtual List<AlbumArtist> AlbumArtists { get; set; }
public virtual List<Artist> Artists { get; set; }
public virtual List<Genre> Genres { get; set; }
public virtual List<Song> Songs { get; set; }
}
public class AlbumArtist
{
public int Id { get; set; }
public string Title { get; set; }
public virtual List<Album> Albums { get; set; }
public virtual List<Artist> Artists { get; set; }
public virtual List<Genre> Genres { get; set; }
public virtual List<Song> Songs { get; set; }
}
public class Artist
{
public int Id { get; set; }
public string Title { get; set; }
public virtual List<AlbumArtist> AlbumArtists { get; set; }
public virtual List<Album> Albums { get; set; }
public virtual List<Genre> Genres { get; set; }
public virtual List<Song> Songs { get; set; }
}
public class Genre
{
public int Id { get; set; }
public string Title { get; set; }
public virtual List<AlbumArtist> AlbumArtists { get; set; }
public virtual List<Album> Albums { get; set; }
public virtual List<Artist> Artists { get; set; }
public virtual List<Song> Songs { get; set; }
}
public class Song
{
public int Id { get; set; }
public string Title { get; set; }
public virtual List<AlbumArtist> AlbumArtists { get; set; }
public virtual List<Album> Albums { get; set; }
public virtual List<Artist> Artists { get; set; }
public virtual List<Genre> Genres { get; set; }
}
As you can see, there are a lot of many-to-many relationships. I populate my entities and then try to save them to DbContext in that way:
_albumArtists.ForEach(delegate(AlbumArtist albumArtist)
{
if (albumArtist.Id == 0)
{
_dbContext.Entry(entity).State = EntityState.Added;
_dbContext.SaveChanges();
}
else
{
_dbContext.Entry(entity).State = EntityState.Modified;
_dbContext.SaveChanges();
}
});
...
or in that way:
_albumArtists.ForEach(delegate(AlbumArtist albumArtist)
{
if (albumArtist.Id == 0)
{
_dbContext.Entry(entity).State = EntityState.Added;
}
else
{
_dbContext.AlbumArtists.State = EntityState.Modified;
}
});
_dbContext.SaveChanges();
...
It takes forever to save my entities to DbContext. I even tried to do the following:
Configuration.AutoDetectChangesEnabled = false;
But it didn't helped. By the way, there are for about 17 000 Songs and 1 700 Albums.
What is wrong???
Please help!
PS
Here is my full code: https://github.com/vjacheslavravdin/PsyTrance/blob/master/PsyTrance/Program.cs Maybe you can suggest how to simplify it.
Thanks!