【发布时间】:2013-02-08 23:59:45
【问题描述】:
我有一个 Game 模型,它附加了许多 Organizer 模型。这是我的模型:
public class Organizer
{
public int ID { get; set; }
public string Name { get; set; }
public List<Game> Games {get; set; }
}
public class Game
{
public int ID { get; set; }
public string Name { get; set;}
public List<Organizer> Organizers { get; set; }
}
我正在尝试获取包含特定组织者的所有游戏。例如,我可能有一些这样的数据:
Game
ID Name
-- ----
1 Soccer
2 Baseball
Organizer
ID Name
-- ----
1 John
2 Barry
GameOrganizer
GameID OrganizerID
------ -----------
1 1
2 1
这是我尝试使用的代码:
Organizer thisOrganizer = db.Organizers.Single(o => o.ID == 1);
var gamesQuery = db.Games
.Where(game => game.Organizers.Contains(thisOrganizer))
.Select(g => new { ID = g.ID, Name = g.Name });
这给了我一个错误:
在此上下文中仅支持原始类型。
我明白这意味着什么,但我不知道如何以不同的方式表达它。我最接近的是:
var gamesQuery = db.Games
.Where(game => game.Organizers
.Any(gO => gO.ID == 1));
但这只是什么都不返回。我到处看了看,但一切都处理事先已经知道的字符串数组。
那么,如果没有模型对象,我该如何表达呢?
【问题讨论】:
-
您的 Organizer 类中没有
Games属性吗?这是代码优先吗?你能发布这两个课程吗? -
@Jobo Organizer 上有一个 Games 属性。这是代码优先。我会补课的。
-
那么我认为 abatishchev 的答案应该是正确的方法。
标签: c# entity-framework exception-handling linq-to-entities