2015-02-23 1021 views
0

在EF中使用代码优先方法为我的数据库种子时出现问题。自从我使用AddOrUpdate方法后,我发现这很奇怪。代码如下:Seed方法使用AddOrUpdata和DropCreateAlways(代码优先,EF)持续生成重复数据

using System; 
using System.Collections.Generic; 
using System.Data.Entity; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace MovieModel 
{ 
    public class MovieContext : DbContext 
    { 
     public MovieContext() : base("name=MovieContext") 
     { 
      Database.SetInitializer<MovieContext>(new DropCreateDatabaseIfModelChanges<MovieContext>()); 
     } 

     public DbSet<Movie> Movies { get; set; } 
     public DbSet<Genre> Genres { get; set; } 
    } 
} 

我也尝试过使用DropCreateDatabaseAlways,但它从不放弃它。我还调整了我的模型,并为新类生成了一张新表,但旧数据仍驻留并重新添加了重复数据。

和种子的方法和类:

namespace MovieModel.Migrations 
{ 
    using System; 
    using System.Collections.Generic; 
    using System.Data.Entity; 
    using System.Data.Entity.Migrations; 
    using System.Linq; 

    internal sealed class Configuration : DbMigrationsConfiguration<MovieModel.MovieContext> 
    { 
     public Configuration() 
     { 
      AutomaticMigrationsEnabled = true; 
     } 

     protected override void Seed(MovieModel.MovieContext context) 
     { 
      var genres = new List<Genre> 
      { 
       new Genre{Description = "Action"}, 
       new Genre{Description = "Thriller"}, 
       new Genre{Description = "Fantasy"}, 
       new Genre{Description = "Horror"}, 
       new Genre{Description = "Science Fiction"} 
      }; 

      genres.ForEach(g => context.Genres.AddOrUpdate(g)); 
      context.SaveChanges(); 
     } 
    } 
} 

注:我还没有提出申请,但迄今为止我已经使用软件包管理器控制台使用Update-Database命令拼命地跑了。迁移已启用。

回答

0

你需要指定在AddOrUpdate关键:

genres.ForEach(g => context.Genres.AddOrUpdate(g => g.Description, g)); 

你也可以只检查它们是否已经存在:如果你用另一个字母代替,例如

if (!context.Genres.Any()) 
{ 
    // Move your seed code here 
} 
+0

该解决方案的工作原理:流派.ForEach(g => context.Genres.AddOrUpdate(u => u.Description,g));现在,当我创建一个流派时,我添加了一个电影列表。这工作。当我创作电影时,我也创建了导演,但是当我创建相同的导演时,例如Silvester Stallone和Expandables I和II,好老的Sly在数据库中出现了两次。任何方式来避免这种情况? – Redesign1991 2015-02-23 17:19:56

+0

是的,在保存电影之前,您需要确保将导演关联到上下文。请参阅将现有实体附加到上下文中:https://msdn.microsoft.com/en-us/data/jj592676.aspx – 2015-02-23 17:24:04