2016-11-14 1 views
0

코드 첫 번째 마이 그 레이션을 사용하여 데이터베이스에 시드했습니다. 그러나 시드 된 데이터를 index.html에서 볼 때 데이터가 복제됩니다.시드 된 데이터가 첫 번째 마이 그 레이션 코드

내부 밀봉 클래스 구성 :

이 구성 파일은 I 데이터 시딩이다 DbMigrationsConfiguration { 공개 구성() { AutomaticMigrationsEnabled = 거짓을; }

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에서 키를 지정해야합니다.

// 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가)와 같이 오류가 생각 빨간색으로 강조 표시 : new {p.ISBN, p.Title} –

+0

죄송합니다. 코드를 실수로 복사했습니다. 컬렉션을 이미 만든 경우에는 foreach가 필요하지 않습니다. 편집을 참조하십시오. –

+0

감사합니다. 작동하지 않는 코드를 시도했습니다. 다음 코드의 책은 오류로 표시됩니다. context.Books.AddOrUpdate (p => new {p.ISBN, p.Title}, books); –