在实体框架中播种多对多数据 [英] Seed Many-to-Many Data in Entity Framework

查看:35
本文介绍了在实体框架中播种多对多数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我首先使用代码,并且书名和类别之间存在多对多关系.在开发过程中播种数据的最佳方法是什么?如果我添加同一类别的两本书,则种子"逻辑会将类别两次添加到类别表中.我可以将类别分别添加到类别"表中,但是然后如何在关键字的图书集中指定现有的类别记录.

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

关键是要与书本创建分开建立类别对象,然后在创建ICollection时使用这些对象

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));

即使我仅填充上下文.RecipesDbSet仍将填充Categories表和CategoryRecipes表,

Even though I only populate the context.Recipes DbSet, the Categories table gets populated and CategoryRecipes table, both get populated correctly.

谢谢Goran Obradovic

Thank you Goran Obradovic

这篇关于在实体框架中播种多对多数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆