C# Web Api公开特定属性而不是外键
我不熟悉C#和实体框架,有以下问题 我有一个球员和一个团队模型:C# Web Api公开特定属性而不是外键,c#,rest,asp.net-web-api,C#,Rest,Asp.net Web Api,我不熟悉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 {
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; }
}
但是我想要
{
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);
}
public异步任务GetPlayer(int-id)
{
Player-Player=wait db.Players.FindAsync(id);
if(player==null)
{
返回NotFound();
}
返回Ok(播放器);
}
首先将您的玩家等级更改为引用父队,而不仅仅是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; }
}
通过创建仅包含要返回的类型的属性的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; }
}