Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Seed Many-to-Many Data in Entity Framework

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.

like image 650
pthalacker Avatar asked Jun 19 '11 19:06

pthalacker


1 Answers

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

like image 83
pthalacker Avatar answered Sep 20 '22 13:09

pthalacker