Entity Framework 6 inserting duplicate values

.net c# ef-code-first entity-framework entity-framework-6

Accepted Answer

If two entities point to the same database row, they are considered to be the same from an EF perspective. Specifically, two entities must share non-zero keys.

If you only desire one thing,Genre If you have an entity with the name "rock," you should add the exact same genre entity to the second artist genres collection. Alternatively, you can have two entities; however, both must have non-zero ids. You probably have someAdd expansion technique that adds a new genre to an artist's repertoire:

public static void Add(this ICollection<Genre> genres, string name)
    genres.Add(new Genre { Name = name });

Each time you call this method, independent instances of genres will be created. The new entities' ids will be equal to zero as a result, and EF will regard them as separate entities. E.g.

 a1.Genres.Add(new Genre { Name = "rock" });
 a1.Genres.Add(new Genre { Name = "rock" });

EF will discover two objects in the genres collection while saving changes. EF will verify entity ids and produce the necessary SQL queries. It will generate an INSERT query if id is zero. If the ID is not zero, EF will produce a UPDATE query. You will have two inserts in this situation (a little simplified - see comment below). How can you solve that? For both performers, you can use the exact same genre entity:

var rock = new Genre { Name = "rock" };
var a1 = new Artist { Name = "a1" };
var a2 = new Artist { Name = "a2" };

You can use an existing "rock" row in the database rather than creating a new one if you don't want to add a new one:

var rock = db.Genres.FirstOrDefault(g => g.Name == "rock") ?? new Genre { Name = "rock" };
2/1/2016 8:18:11 PM

Popular Answer


Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow