种子数据是重复代码的第一次迁移

时间:2016-11-14 00:00:57

标签: asp.net-mvc ef-migrations

我使用代码首次迁移来播种数据库,但是当我查看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();


    }
}

}

我真的不确定我是不是错了,花了好几天! 真的很感激任何人的帮助!谢谢!

1 个答案:

答案 0 :(得分: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/