Seed Many-to-Many Data in Entity Framework

前端 未结 1 1187
后悔当初
后悔当初 2021-02-08 23:44

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

相关标签:
1条回答
  • 2021-02-09 00:47

    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

    0 讨论(0)
提交回复
热议问题