如何创建和更新与EF的许多关系 [英] How Do I Create And Update A Many To Many Relationship With EF

查看:140
本文介绍了如何创建和更新与EF的许多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Entity Framework与SQL Server。我有两张桌子之间有很多关系。我已经创建了一个连接表,只有2个表的主键字段。在设计器中,这两个表格现在有一个导航属性,另一个是返回类型为X的集合,其中X是另一个实体。到目前为止,一切都是应该的。设置看起来正确。

 任务任务产品
========== ========= === =======
TaskID TaskID ProductID
说明ProductID名称

并不是每个任务都会有一个与之相关联的产品或产品。如果该任务没有关联的产品,那么在任务表的产品导航属性中分配什么?



我是否使用Product实体建立一个EntityCollection集合,当我有产品实体时,将其分配给任务实体上的产品导航属性?



在更新(添加,删除和更改)到任务实体,我和其他任何集合一起工作吗?有什么特别的事情需要注意吗?



我将对在实体框架中与多对多关系有任何帮助有兴趣。



编辑(11/17/2009)

我学到的一件事是,通过一个连接表,多个关系工作,两个字段在连接表中需要将其标记为主键;

解决方案

MSDN具有管理多对多关系的良好文档实体框架:



http://msdn.microsoft.com/en-us/library/bb738695.aspx



插入的说明性指导是调用添加方法,并指定相关对象(与一对多关系的实体引用设置Value属性。)



更新仅处理像任何其他EF更新...加载欲望d对象,设置更改的属性,并在上下文中调用SaveChanges。



删除操作也一样,在上下文中调用DeleteObject,然后调用SaveChanges。


I am using the Entity Framework with SQL Server. I have a many to many relationship between 2 tables. I have created a join table with just the primary key fields of the 2 tables. In the designer, the 2 tables now have a navigation property to the other with return types of Collection of X where X is the other entity. So far, everything just as it should be. The setup looks correct.

Task           TaskProducts     Product
==========     ============     =======
TaskID         TaskID           ProductID
Description    ProductID        Name

Not every task will have a product or products associated with it. What do I assign to the Products navigation property of the Task table when there is no associated Product for that Task?

Do I build up a EntityCollection collection with the Product entities and assign that to the Products navigation property on the Task entity when I do have Product entities?

When doing updates(adding, removing and changing) to the Products navigation property on the Task entity, do I work with it like any other collection? Are there any special things to look out for?

I would be interested in any help working with many to many relationships in the Entity Framework.

Edit(11/17/2009)
One thing I learned is that to a many to many relationship work with a join table, BOTH fields in the join table need to be marked as primary keys;

解决方案

MSDN has good documentation on managing many-to-many relationships in the Entity Framework:

http://msdn.microsoft.com/en-us/library/bb738695.aspx

The prescriptive guidance for inserts is to call the "Add" method on the entity collection and specify the related object (versus setting the Value property on the entity reference for a one-to-many relationship.)

Updates are handled just like any other EF update... load the desired object, set the changed properties and call SaveChanges on the context.

Deletes are handled the same as well, call DeleteObject on the context and then SaveChanges.

这篇关于如何创建和更新与EF的许多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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