I have the following simplified many-to-many related models:
public class Singer
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Song> Songs { get; set; }
}
public class Song
{
[Key]
public int Id { get; set; }
public string Title { get; set; }
public virtual ICollection<Singer> Singers { get; set; }
}
The DB tables created are below:
dbo.Singers
Id
Name
dbo.Songs
Id
Title
dbo.SingerSongs
Singer_Id
Song_Id
I used the following seed code to add items to already populated tables while preventing duplicates:
public static void SeedNewSingerAndSong(AppContext context)
{
// Create new song
Song newSong = new Song() { Title = "New Song" };
context.Songs.AddOrUpdate(
item => item.Title,
newSong
);
context.SaveChanges();
// Create new Singer
Singer newSinger = new Singer() { Name = "New Singer" };
context.Singers.AddOrUpdate(
item => item.Name,
newSinger
);
context.SaveChanges();
}
Recently, I updated the seed code to link "New Singer" to "Existing Song" and "New Song" as follows:
public static void SeedNewSingerAndSong(AppContext context)
{
// Create new song
Song newSong = new Song() { Title = "New Song" };
context.Songs.AddOrUpdate(
item => item.Title,
newSong
);
context.SaveChanges();
// Find existing songs
Song foundExistingSong = context.Songs.Single(x => x.Title == "Existing Song");
Song foundNewSong = context.Songs.Single(x => x.Title == "New Song");
// Create new Singer
Singer newSinger = new Singer() { Name = "New Singer" };
// Assign songs to new Singer
newSinger.Songs.Add(foundExistingSong);
newSinger.Songs.Add(foundNewSong);
context.Singers.AddOrUpdate(
item => item.Name,
newSinger
);
context.SaveChanges();
}
This doesn't work (no relationship gets added) probably because "New Singer" has already been added previously. If I manually delete "New Singer", the singer gets added together with the relationships when seeding. However, I don't want to delete items just so I could add relationships. How do I make this seed work?
Update: The problem with duplicate "New Song" when "New Song" already exists prior to seeding has been fixed with the updated code.