2016-11-14 133 views
0

我已經使用代碼第一次遷移種子數據庫,但是我注意到當我在index.html中查看種子數據時,數據被複制。種子數據是重複代碼第一次遷移

這是在配置文件是我接種數據:

內部密封類配置:DbMigrationsConfiguration { 公共配置() { AutomaticMigrationsEnabled = FALSE; }

protected override void Seed(OnlineBookStore.Models.OnlineBookStoreDB context) 
    { 

     var books = new System.Collections.Generic.List<Book> 
     { 
      new Book { 

     BookStatus = new BookStatus { Status = "New" }, 
      Genre = new Genre { Name = "Thriller" }, 
      Author = new Author { Name = "Paula Hawkins" }, 
      Title = "The Girl On The Train", 
      Description = "Rachel catches the same commuter train   morning. ", 
      ISBN = 0552779776, 

      }, 


     new Book 
     { 
      BookStatus = new BookStatus { Status = "Best Seller" }, 
      Genre = new Genre { Name = "Childrens" }, 
      Author = new Author { Name = "Roald Dahl" }, 
      Title = "The Witches", 
      Description = "Beware. Real witches dress in ordinary clothes", 


      ISBN = 0141365471, 

     }, 
     }, 

     }; 

books.ForEach(s =>context.Books.AddOrUpdate(p => new { p.ISBN, p.Title })); 
      context.SaveChanges(); 


    } 
} 

}

我真的不能確定是我錯的,花費數天時間在此! 真的很感謝任何人的幫助!謝謝!

回答

0

您需要在AddOrUpdate中指定密鑰以防止重複,因爲Seed()在每個發佈的更新數據庫都運行。

// build your books collection 
    var books = new [] 
    { 
     new Book { 

    BookStatus = new BookStatus { Status = "New" }, 
     Genre = new Genre { Name = "Thriller" }, 
     Author = new Author { Name = "Paula Hawkins" }, 
     Title = "The Girl On The Train", 
     Description = "Rachel catches the same commuter train   morning. ", 
     ISBN = 0552779776, 

     }, 


    new Book 
    { 
     BookStatus = new BookStatus { Status = "Best Seller" }, 
     Genre = new Genre { Name = "Childrens" }, 
     Author = new Author { Name = "Roald Dahl" }, 
     Title = "The Witches", 
     Description = "Beware. Real witches dress in ordinary clothes", 


     ISBN = 0141365471, 

    }, 
    }, 

    };  


context.Books.AddOrUpdate(p => new { p.ISBN, p.Title }, books); 
context.SaveChanges(); 

http://thedatafarm.com/data-access/take-care-with-ef-4-3-addorupdate-method/

+0

感謝,我這樣做,但它指出p沒有在當前的背景下存在的,在下面的代碼中,p是被我認爲錯誤是因爲它是(在P)突出顯示紅色:新{p.ISBN,p.Title} –

+0

對不起,無意識地複製了代碼。如果你已經建立了一個集合,你不需要foreach。請參閱編輯。 –

+0

謝謝,試過你的代碼,它不起作用,下面的代碼中的書出現爲錯誤,context.Books.AddOrUpdate(p => new {p.ISBN,p.Title},books); –

相關問題