使用多对多关系在实体框架中获取错误

时间:2014-03-11 12:22:58

标签: .net linq entity-framework

我有两个名为Buttons and Tiles的表,具有多对多关系,如下所示:

Buttons            *-----------
    ButtonID                  |
    Title                     |
                              |
Tiles              *-----------
    TileID
    Title

现在我试图查询类似于:

b = new ObservableCollection<Buttons>(from x in db.Buttons
                                      where x.Tile == SelectedTileObj
                                      select x);

但是我收到如下所述的错误:

Unable to create a constant value of type 'Data.Tiles'.
Only primitive types or enumeration types are supported in this context.

1 个答案:

答案 0 :(得分:2)

假设TileID是主键,您可以采取另一种方法:

  • 选择您感兴趣的图块(具有正确的ID)
  • 使用导航属性,获取与上述图块相关联的按钮

    var tiles = db.Tiles.Where(t => t.TileId == SelectedTileObj.TileId);
    // t.Buttons should be the navigation property for retrieving associated buttons
    var buttons = tiles.SelectMany(t => t.Buttons);
    var b = new ObservableCollection<Buttons>(b);