Web Api公开特定的属性而不是外键
本文关键字:属性 Api Web | 更新日期: 2023-09-27 18:18:03
我是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数组返回,其中球员的球队是球队表的ID(外键)。不过,如果能返回球队名称就好了。我怎样才能优雅地做到这一点?
{
ID: 7
FirstName: "Sidney"
LastName: "Crosby"
TeamID: 1
}
但是我想要
{
ID: 7
FirstName: "Sidney"
LastName: "Crosby"
TeamID: Denver Broncos
}
Web Api Controller如下:
public async Task<IHttpActionResult> GetPlayer(int id)
{
Player player = await db.Players.FindAsync(id);
if (player == null)
{
return NotFound();
}
return Ok(player);
}
首先改变你的球员类来引用父队而不仅仅是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; }
}