Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/268.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Web Api公开特定属性而不是外键_C#_Rest_Asp.net Web Api - Fatal编程技术网

C# Web Api公开特定属性而不是外键

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 {

我不熟悉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; }
}
但是我想要

{
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; }
    }