I am using code first and have a many-to-many开发者_开发百科 relationship between Book Titles and Categories. What is the best way to seed the data during development? If I add two books in the same category, the Seed logic adds the category twice to the category table. I can add categories separately to the Category table, but then how do I specify that existing category records in the books collection of keywords.
I credit this blog entry with showing me the way http://blog.goranobradovic.com/2011/06/asp-net-mvc3-app-part-1-entity-framework-and-code-first/comment-page-1/#comment-1663
The key is to establish the category objects separately from the book creation and then use those objects when creating the ICollection
var catCSharp = new Category {Name="CSharp"};
var catEF = new Category {Name="Entity Framework"};
var Categories = new List<Category> () {catCSharp, catEF};
var Books = new List<Book>();
Books.Add(new Book {Title="Entity Framework",
Categories=new List<Category>() {catCSharp, catEF}};
Books.ForEach(b => context.Books.Add(b));
Even though I only populate the context.Recipes DbSet, the Categories table gets populated and CategoryRecipes table, both get populated correctly.
Thank you Goran Obradovic
精彩评论