Entity Framework 6 inserting duplicate values
From EF point of view two entities are same if they are pointing to same row in database. I.e. two entities should have same non-zero keys.
If you want to have only one Genre
entity with name "rock", then you should add exactly same genre entity to second artist genres collection or you can have two entities, but they should have same non-zero ids. I suppose you have some Add
extension method which creates new genre and adds it to artist's genres:
public static void Add(this ICollection<Genre> genres, string name)
{
genres.Add(new Genre { Name = name });
}
This will create independent instances of genres each time you call this method. Thus ids of created entities will be equal to zero, EF will treat them as different entities. E.g.
a1.Genres.Add(new Genre { Name = "rock" });
a1.Genres.Add(new Genre { Name = "rock" });
During saving changes EF will find two objects in genres collection. EF will check entities ids and generate appropriate SQL queries. If id is zero, it will generate INSERT query. For non-zero id EF will generate UPDATE query. In this case you will have two inserts (a little simplified - see comment below). How to fix that? You can use exactly same genre entity for both artists:
var rock = new Genre { Name = "rock" };
var a1 = new Artist { Name = "a1" };
a1.Genres.Add(rock);
var a2 = new Artist { Name = "a2" };
a2.Genres.Add(rock);
If you don't want to insert new 'rock' row to database, then you can use existing one instead of creating new:
var rock = db.Genres.FirstOrDefault(g => g.Name == "rock") ?? new Genre { Name = "rock" };