使用 LINQ 从 ID 引用的表中获取记录名称
我在进行一些 MVC 测试时遇到了问题。所以目前我有两张桌子,一张称为联赛,一张称为球队。
在联赛中,我有 LeagueID、LeagueName;在团队中,我有 TeamID 和 TeamName。然后我有另一个名为 LeagueTeams 的表,其中包含 LeagueTeamID、fk_LeagueID 和 fk_TeamID。
现在在我的 ViewData 中,我引用 Teams 表,因此我有如下内容:-
@foreach (var item in Model.Teams) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.TeamName)
</td>
<td>
@Html.DisplayFor(modelItem => item.LeagueTeams)
</td>
</tr>
现在 item.LeagueTeams 是例如 1,即 LeagueTeamID。我怎样才能获得这段代码中的联赛名称?我是否需要调用对其他内容的引用,或创建 linq 语句?
更新
我在我的控制器中想出了这个,但我仍然有一个问题:-
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
TeamsData model = new TeamsData();
var _Teams = (from t in db.Teams
from tl in db.LeagueTeams
where t.LeagueTeams.Contains(tl.League.LeagueID)
select t);
model.Teams = _Teams;
return View(model);
}
但是代码在 tl.League.LeagueID 上抛出错误,告诉我:-
“无法从 'int' 转换为 'MyProject.Models.LeagueTeam' “
任何帮助都将非常感激,因为我似乎在这里有点迷失了!
感谢您的帮助和时间
I encountered a problem, while doing some MVC testing. So at the moment I have 2 tables, one called Leagues and one called Teams.
In Leagues I have LeagueID, LeagueName, and in Teams I have TeamID and TeamName. Then I have another table called LeagueTeams which contains the LeagueTeamID, fk_LeagueID and fk_TeamID.
Now in my ViewData, I am referencing the Teams table so I have something like the following :-
@foreach (var item in Model.Teams) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.TeamName)
</td>
<td>
@Html.DisplayFor(modelItem => item.LeagueTeams)
</td>
</tr>
Now item.LeagueTeams is for example 1, which is the LeagueTeamID. How can I get the League Name in this code? Do I need to call a reference to something else, or create a linq statement?
UPDATE
I came up with this in my Controller but I still have a problem :-
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
TeamsData model = new TeamsData();
var _Teams = (from t in db.Teams
from tl in db.LeagueTeams
where t.LeagueTeams.Contains(tl.League.LeagueID)
select t);
model.Teams = _Teams;
return View(model);
}
However the code is throwing an error on tl.League.LeagueID, telling me :-
"cannot convert from 'int' to 'MyProject.Models.LeagueTeam'"
Any help would really be appreciated since I seem to be a bit lost here!
Thanks for your help and time
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
编辑:
Edit: