Yianni
Yianni
CC#
Created by Yianni on 11/16/2023 in #help
EFCore: don't require primary key for POST
Howdy, forgive me if I don't have the terminology down yet, I just started following this guide recently: https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-8.0&preserve-view=true&tabs=visual-studio So I've created a Model:
c#
public class User
{
[Key]
public required string Guid { get; set; }

[Required]
public required string Name { get; set; }

[Required]
public required string Tag { get; set; }

public DateTime LastUpdate { get; set; }
}
c#
public class User
{
[Key]
public required string Guid { get; set; }

[Required]
public required string Name { get; set; }

[Required]
public required string Tag { get; set; }

public DateTime LastUpdate { get; set; }
}
And here's my code for the Controller. Note that I am assigning the primary key within this method.
c#
[HttpPost]
public async Task<ActionResult<User>> PostUser(User user)
{
User newUser = new User()
{
Guid = Guid.NewGuid().ToString(),
Name = name,
Tag = tag,
LastUpdate = DateTime.Now
};

_context.Users.Add(newUser);
return CreatedAtAction(nameof(GetUsers), user);
}
c#
[HttpPost]
public async Task<ActionResult<User>> PostUser(User user)
{
User newUser = new User()
{
Guid = Guid.NewGuid().ToString(),
Name = name,
Tag = tag,
LastUpdate = DateTime.Now
};

_context.Users.Add(newUser);
return CreatedAtAction(nameof(GetUsers), user);
}
My problem is that I do not want the primary key (Guid) to be required in the request body to send the POST request. Is there any way around this? I just want my POST request body to look like the following example:
{
"Name": "Jimbo",
"Tag": 12345
}
{
"Name": "Jimbo",
"Tag": 12345
}
Omitting the Guid from this results in the following error: "JSON deserialization for type 'api.Models.User' was missing required properties, including the following: guid"
13 replies