实体框架迁移种子方法复制记录

时间:2018-10-21 22:37:25

标签: entity-framework ef-migrations

数据模型:歌曲-艺术家(N:N)

我正在尝试播种数据库,但是由于种种原因,播种方法运行后我的艺术家变得重复。我不确定为什么...

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

CreateSong方法:

    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结果: 3位艺术家,而我只期待一位。 this documentation resource

尝试使用context.Artists.Add(artist);和不使用,但结果保持不变

1 个答案:

答案 0 :(得分:1)

问题出在这里:

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

此查询系统地命中数据库。但是,在SaveChanges之前,数据库为空。

因此,您应该执行以下操作:

//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);
}