0

I wan't to create a "Group" using http POST request. The User isn't existing, so it should also be created. But the "item" in received by Post is alway null. When I don't post a user or an empty users array, it works.

Here is my Model:

public class User
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public virtual Group Group { get; set; }
}

public class Group
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public virtual List<User> Users { get; set; }
}

And the Post Method:

// POST api/<controller>
[HttpPost]
[ProducesResponseType(typeof(Group), StatusCodes.Status200OK)]
public async Task<IActionResult> Post([FromBody] Group item)
{
    EntityEntry<Group> entityEntry = this._launcherContext.Database.Add(item);
    this._launcherContext.Database.SaveChanges();

    return Ok(entityEntry.Entity);
}

And at least the json body:

{
  "name": "TestGroup",
  "users": [
    {
      "name": "Threepwood, Guybrush"
    }
  ]
}

1 Answer 1

0

If you want to create Group without User create a GroupPost class.

public class GroupPost
{
    public GroupPost(){
    Users = new List<UserPost>();
    }
    public string Name { get; set; }
    public List<UserPost> Users { get; set; }
}
public class UserPost
{
    public string Name { get; set; }

}    

[HttpPost]
[ProducesResponseType(typeof(Group), StatusCodes.Status200OK)]
public async Task<IActionResult> Post([FromBody] GroupPost item)
{
    Group newItem = new Group
    {
     Name=item.Name,         
    };
    foreach(var user in item.Users){
    User newUser = new User{
    Name=user.Name
    };
    newItem.Add(newUser);
    }
    EntityEntry<Group> entityEntry = this._launcherContext.Database.Add(newItem);
    this._launcherContext.Database.SaveChanges();

    return Ok(entityEntry.Entity);
}

Then you can post your data without User list

2
  • But I wan't to create a group with users. My example only works without users. The users should also be created. Mar 11, 2020 at 12:09
  • Okey,my bad I change the answer. Mar 11, 2020 at 12:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.