asp.net web api one to many crud

Anonymous
2022-09-11T13:59:31.373+00:00

I created the webapi to list all players

https://github.com/KalyanAllam/Players

I need code to

1)Get one player with id

2)Create a new player

The player info will be sent in the body in JSON format:

{
"name": "player name 5",
"position": "midfielder",
"playerSkills": [
{
"skill": "attack",
"value": 60
},
{
"skill": "speed",
"value": 80
}
]
}
JSON

The expected result from this endpoint is the created player. The result can also have additional fields, like id's created for the player and the skills ex:

{
"id": 1,
"name": "player name 5",
"position": "midfielder",
"playerSkills": [
{
"id": 1,
"skill": "attack",
"value": 60,
"playerId": 5
},
{
"id": 2,
"skill": "speed",
"value": 80,
"playerId": 5
}
]
}

Update Player:
The app will need to support player update on http://localhost:3000/api/player/{playerId} where {playerId} is the id of the player that is being updated.

The player info will be sent in the body in JSON format:

{
"name": "player name updated",
"position": "midfielder",
"playerSkills": [
{
"skill": "strength",
"value": 40
},
{
"skill": "stamina",
"value": 30
}
]
}
JSON

The expected result from this endpoint is the updated player. The result can also have additional fields, like id's created for the player and the skills ex:

{
"id": 1,
"name": "player name updated",
"position": "midfielder",
"playerSkills": [
{
"id": 3,
"skill": "strength",
"value": 40,
"playerId": 1
},
{
"id": 4,
"skill": "stamina",
"value": 30,
"playerId": 1
}
]
}
JSON

Delete Player:
The app will need to support player deletion on http://localhost:3000/api/player/{playerId} where {playerId} is the id of the player that is being deleted.

Important!

The endpoint to delete the player should be protected using Bearer token in the Authorization Header. The value of the Authorization Header should be:

Bearer SkFabTZibXE1aE14ckpQUUxHc2dnQ2RzdlFRTTM2NFE2cGI4d3RQNjZmdEFITmdBQkE=

ASP.NET API
ASP.NET API
ASP.NET: A set of technologies in the .NET Framework for building web applications and XML web services.API: A software intermediary that allows two applications to interact with each other.
296 questions
0 comments No comments
{count} votes

Accepted answer
  1. XuDong Peng-MSFT 10,101 Reputation points Microsoft Vendor
    2022-09-12T08:39:17.497+00:00

    Hi @Anonymous ,

    Based on your description, it looks like you want to implement database CRUD via .NET WebApi and entity framework.

    In fact, in the official documentation, you can find a simple example of it. Just like this doc (with example): Using Web API 2 with Entity Framework 6 Tutorial Series.

    In your case, I think your main problem is that you need to process the request data during the request process, and then do CRUD operations in these two tables separately. For example, you will try to insert a record of player. In the json data you provided, it actually contains the data of two tables, you need to get it in [FromBody] or HttpRequestMessage, and do the necessary processing, like this:

       public IHttpActionResult Post([FromBody] players player)  
               {  
                   if (!ModelState.IsValid)  
                   {  
                       return BadRequest(ModelState);  
                   }  
                   else  
                   {  
                       //insert new record into database.  
                       db.Players.Add(player);  
                       db.SaveChanges();  
                       foreach (var skill in player.playerSkills)  
                       {  
                           //set the ID of each skill  
                           skill.playerId = player.Id;  
                           db.PlayerSkills.Add(skill);  
                           db.SaveChanges();  
                       }  
                       return Ok(player);  
                   }  
               }  
    

    You need to manually assign the playerId property to each playerSkill object. So it mainly depends on your table structure design and logical processing.

    In addition, for authorization token, you can simply refer to this documentation: Authentication and Authorization in ASP.NET Web API.
    Best regards,
    Xudong Peng


    If the answer is the right solution, please click "Accept Answer" and kindly upvote. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

4 additional answers

Sort by: Most helpful
  1. Anonymous
    2022-09-12T12:20:34.32+00:00

    Thanks @XuDong Peng-MSFT it works.

    0 comments No comments

  2. Anonymous
    2022-09-12T13:19:48.387+00:00

    @XuDong Peng-MSFT

    If you have something for put that would be helpful .update on http://localhost:3000/api/player/{playerId} where {playerId} is the id of the player that is being updated.

    {
    "name": "player name updated",
    "position": "midfielder",
    "playerSkills": [
    {
    "skill": "strength",
    "value": 40
    },
    {
    "skill": "stamina",
    "value": 30
    }
    ]
    }

    {
    "id": 1,
    "name": "player name updated",
    "position": "midfielder",
    "playerSkills": [
    {
    "id": 3,
    "skill": "strength",
    "value": 40,
    "playerId": 1
    },
    {
    "id": 4,
    "skill": "stamina",
    "value": 30,
    "playerId": 1
    }
    ]
    }


  3. Anonymous
    2022-09-13T09:21:29.497+00:00

    @XuDong Peng-MSFT

    Thank you, I modified the code a bit and can now update the player , I am still working on the playerskills

    [HttpPut]
    public IHttpActionResult Put(int id, [FromBody] players player)
    {
    if (!ModelState.IsValid)
    {
    return BadRequest(ModelState);
    }
    else
    {
    //find record based on playerId and update
    var updateplayer = db.Players.First(p => p.Id == id);
    updateplayer.Name = player.Name;
    updateplayer.position = player.position;
    db.SaveChanges();

                /*  
               foreach (var playerSkill in player.playerSkills)  
                {  
                    //update playerSkill based on skillId  
                    var currectSkill = db.PlayerSkills.First(s => s.playerId == playerSkill.Id);  
                    currectSkill.skill = playerSkill.skill;  
                    currectSkill.value = playerSkill.value;  
                    db.SaveChanges();  
                }  
                */  
                return Ok(player);  
            }  
        }  
    
    0 comments No comments

  4. Anonymous
    2022-09-13T10:38:35.823+00:00

    @XuDong Peng-MSFT

    Please suggest on how to delete? what method should be used I would try to add cascade delete to second table.

    public IHttpActionResult Delete(int id)
    {
    var deleteplayer = db.Players.First(p => p.Id == id);

            return Ok();  
        }