Seed Many-to-Many Data in Entity Framework

人走茶凉 提交于 2021-02-17 22:25:32

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/6404629/seed-many-to-many-data-in-entity-framework

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!