Reinard
Reinard

Reputation: 3654

entity framework migration seed method duplicating records

Data model: Song - Artists (N:N)

I'm trying to seed my database, but for some reason my Artists are getting duplicate after the seed method has ran. I'm not sure why...

    CreateSong("COLDPLAY", "Viva la vida", context);
    CreateSong("COLDPLAY", "UP & UP", context);
    CreateSong("COLDPLAY", "UP & UP", context);

CreateSong method:

    public Song CreateSong(String artistName, String title, NeosicDbContext context)
    {
        var ret = context.Songs.FirstOrDefault(s => s.Title == title && s.Artists.FirstOrDefault(a => a.Name == artistName) != null);
        if(ret != null)
        {
            return ret;
        }

        **var artists = new List<Artist>();
        var artist = context.Artists.FirstOrDefault(a => a.Name == artistName);
        if (artist == null)
        {
            artist = new Artist { Name = artistName };
            context.Artists.Add(artist);
        }
        artists.Add(artist);**
        var tags = new List<Tag>();
        tags.Add(defaultTag);

        ret = new Song {
            Title = title,
            Artists = artists,
            Tags =  tags
        };
        context.Songs.Add(ret);
        //context.MarkAsModified(ret);
        return ret;
    }

Db result: 3 artists, while I'm only expecting one. enter image description here

Tried both with context.Artists.Add(artist); and without but results remains the same

Upvotes: 0

Views: 52

Answers (1)

tschmit007
tschmit007

Reputation: 7800

the problem comes here:

var artist = context.Artists.FirstOrDefault(a => a.Name == artistName);

this query systematically hits the db. But, before SaveChanges, the db is empty.

So, you should do something like:

//check the context (I would like to say the *cache*, but it is a false friend in this case)
var artist = context.Artists.Local.FirstOrDefault(a => a.Name == artistName);
if ( artist == null) {
    //then hit the db
    artist = context.Artists.FirstOrDefault(a => a.Name == artistName);
}

Upvotes: 1

Related Questions