0

First said, this is my first experience using the Entity Framework so I apologize if this ends up being a newbie question. Everything has gone well so far; but, I run into a situation that I am not sure what the best way to handle is.

I need to create a many-to-many relationship; but, the many-to-many table contains more than just the composite key. In this case the Entity Framework does not see to recognize it as a many-to-many structure and so I don't seem to get the easy ability to get the collections without using the intervening table. Is there a better way to do this?

Simplified Example:

  • A Unit can have many boards and a board could have been in many units
  • When it is in a unit we need to record what slot it was in.

Tables:

Unit
 UnitID(PK)
 UnitName

Board
 BoardID(PK)
 BoardName

UnitBoard
 UnitID(PK,FK1)
 BoardID(PK,FK2)
 Slot

When I pull this into my code using an ADO.NET Entity Data Model, I don't see an easy way to get the collection of Boards associated to a Unit from the Unit Entity or visa-versa.

Is there a better way to do this or do I just need to use the associated collection of UnitBoards then use that to build the collection of Units/Boards?

This seems I am probably not the first person to went to do something like this. Ex: I was thinking of Books and Owners wanting to also keep the related BookOwner information (like the purchase date).

4

2 回答 2

1

即使在更新的 Entity Framework 5 中,也没有很好的解决这个问题的方法。如果您有正确的外键关系,您应该能够访问您的板或单元,例如:

Unit.UnitBoards.Boards

或者

Board.UnitBoards.Units

但是如果多对多表在复合键之外有它自己的属性,那么您将没有直接导航属性(多对多导航)。

过滤时,您可以使用IncludeSelect减少数据库调用来包含它们。

var myBoards = From Context.Boards
  .Include(i => i.UnitBoards)
  .Include(i => i.UnitBoards.Select(is => is.Unit))
  .Where(...)
于 2012-10-24T00:25:28.147 回答
1

有没有更好的方法来做到这一点,还是我只需要使用相关的 UnitBoards 集合然后使用它来构建 Units/Boards 的集合?

拥有自定义联结表的唯一方法是像您一样创建实体。您可以让 EF 为您管理多对多关系,因此您可以拥有直接导航集合,或者您可以拥有关系上的自定义属性,但不能同时拥有这两者。

如果您考虑一下原因 - 如果 EF 确实允许您在关系上拥有自定义属性,您将如何访问它?要从 aBoard到达 a Unit,您只需要去Unit.Boards。要从 aUnit到 a Board,那就是Board.Units。您实际上没有任何地方可以为任何个人关系放置插槽属性。

于 2012-10-24T00:22:00.380 回答