2015-02-23 1022 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