【发布时间】:2021-11-01 18:38:39
【问题描述】:
我在 ASP.NET Core 2.2 的实体框架核心中读取相关数据时遇到问题。
我有两个实体 Team 和 Player,因为我处理多对多关系(团队可以有很多玩家,而玩家可以有多个团队),我有连接实体 PlayerAssignments。
在球员索引视图中,我想显示所有球员和他们的信息 - 名字、姓氏和他们被分配到的球队,但我不知道如何解决这个问题,我正在尝试解决这个问题大约两个现在几天。
public class Player
{
public int id { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
public ICollection<PlayerAssignments> PlayerAssignments { get; set; }
}
public class Team
{
public int id { get; set; }
public string name { get; set; }
public string city { get; set; }
public ICollection<PlayerAssignments> PlayerAssignments { get; set; }
}
public class PlayerAssignment
{
public int PlayerID { get; set; }
public int TeamID { get; set; }
public Player Player { get; set; }
public Team Team { get; set; }
}
dbcontext 中的所有内容都类似。
在我的 PlayerController.cs 的 index 方法中:
var player = await _context.Player
.Include(one => one.PlayerAssignment)
.ThenInclude(team => team.Team)
.ThenInclude(teamName => teamName.name)
.ToListAsync();
if(player == null)
{
return NotFound();
}
return View(player);
}
我的索引视图如下所示:
<table class="table">
<thead>
<tr>
<th>
First name
</th>
<th>
Last name
</th>
<th>
Player's teams
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.first_name)
</td>
<td>
@Html.DisplayFor(modelItem => item.last_name)
</td>
<td>
foreach(var assignedTeam in item.PlayerAssignments)
{
@* I just cant figure out code here *@
}
</td>
</tr>
</tbody>
<table>
我需要向所有玩家展示他们的信息以及他们被分配到的球队。但无论我怎么尝试,我都没有写出球员被分配到的球队(他们被填写在数据库中)。
【问题讨论】:
-
我从来没有写出来...你能说得更具体一点吗?错误?出乎意料的数据?等等。
-
在我使用的所有方法中,它都给了我错误或什么也没返回,但是先生的回答如下。 Tiago 帮我找到了问题所在 :) 谢谢大家!
标签: asp.net-core entity-framework-core