种子数据是重复代码第一次迁移
问题描述:
我已经使用代码第一次迁移种子数据库,但是我注意到当我在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();
}
}
}
我真的不能确定是我错的,花费数天时间在此! 真的很感谢任何人的帮助!谢谢!
答
您需要在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/
感谢,我这样做,但它指出p没有在当前的背景下存在的,在下面的代码中,p是被我认为错误是因为它是(在P)突出显示红色:新{p.ISBN,p.Title} –
对不起,无意识地复制了代码。如果你已经建立了一个集合,你不需要foreach。请参阅编辑。 –
谢谢,试过你的代码,它不起作用,下面的代码中的书出现为错误,context.Books.AddOrUpdate(p => new {p.ISBN,p.Title},books); –