开发者

How Do I Create And Update A Many To Many Relationship With EF

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜