question

KALYANAALLAM-4847 avatar image
0 Votes"
KALYANAALLAM-4847 asked XuDongPeng-MSFT commented

asp.net web api one to many crud

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=


dotnet-aspnet-webapi
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

XuDongPeng-MSFT avatar image
0 Votes"
XuDongPeng-MSFT answered

Hi @KALYANAALLAM-4847,

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.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

KALYANAALLAM-4847 avatar image
0 Votes"
KALYANAALLAM-4847 answered KALYANAALLAM-4847 edited

Thanks @XuDongPeng-MSFT it works.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

KALYANAALLAM-4847 avatar image
0 Votes"
KALYANAALLAM-4847 answered XuDongPeng-MSFT commented

@XuDongPeng-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
}
]
}

· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hi @KALYANAALLAM-4847,

In my opinion, it is actually similar to inserting data. You still need to process the two tables separately, query the corresponding data according to playerId and skillsId, and then modify it, like this:

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 == player.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.Id == playerSkill.Id);
                    currectSkill.skill = playerSkill.skill;
                    currectSkill.value = playerSkill.value;
                    db.SaveChanges();
                }
                return Ok(player);
            }
        }

1 Vote 1 ·
KALYANAALLAM-4847 avatar image
0 Votes"
KALYANAALLAM-4847 answered

@XuDongPeng-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);
         }
     }
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

KALYANAALLAM-4847 avatar image
0 Votes"
KALYANAALLAM-4847 answered XuDongPeng-MSFT commented

@XuDongPeng-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();
     }
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hi @KALYANAALLAM-4847 ,

Yes, as you mentioned, cascading delete should be meet your needs. Something like this:

public void Delete(int id)
        {
            //remove  record in players table
            var deleteplayer = db.Players.First(p => p.Id == id);
            db.Players.Attach(deleteplayer);
            db.Players.Remove(deleteplayer);
            db.SaveChanges();
            //remove records in skills table
            var skills = db.PlayerSkills.Where(s => s.playerId == id);
            db.PlayerSkills.RemoveRange(skills);
            db.SaveChanges()
        }

0 Votes 0 ·