我是C#和实体框架的新手,有以下问题。
我有一个玩家和一个团队模型:
public class Player
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int TeamID { get; set; }
}
public class Team
{
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<Player> Players { get; set; }
}
现在我通过rest web api将数据暴露给客户端。但是当我试图获得所有玩家时,会返回一个json数组,其中玩家可以使用#j; team是团队表的ID(外键)。但是,返回团队名称会很不错。我怎样才能优雅地实现这一目标?
{
ID: 7
FirstName: "Sidney"
LastName: "Crosby"
TeamID: 1
}
但我想要
{
ID: 7
FirstName: "Sidney"
LastName: "Crosby"
TeamID: Denver Broncos
}
Web Api控制器如下所示:
public async Task<IHttpActionResult> GetPlayer(int id)
{
Player player = await db.Players.FindAsync(id);
if (player == null)
{
return NotFound();
}
return Ok(player);
}
答案 0 :(得分:1)
首先更改您的玩家类以引用父团队而不仅仅是ID:
public class Player
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual Team Team { get; set; }
}
然后创建一个DTO对象,以在您希望它们的结构中公开所需的属性:
public class PlayerDto
{
public PlayerDto(Player player)
{
FirstName = player.FirstName;
LastName = player.LastName;
TeamName = player.Team.Name;
}
public string FirstName { get; set; }
public string LastName { get; set; }
public string TeamName { get; set; }
}