I have small .Net 5 Web Api project. Code first approach is applied. MS SQL. EF Core.
The problem is - When controller receive model without Id
- it fails with - "One or more validation errors occurred.". If controller received Id: 0
- it is Ok, It works.
The question is - Is it possible to omit Id
property in POST request?
I want to completely omit Id
from request.
Model:
public class Playback
{
public int Id { get; set; }
[Required]
public string Video_Name { get; set; }
[Required]
public string Video_Duration { get; set; }
public string Playback_User { get; set; }
public int Playback_Duration { get; set; }
}
Controller:
public async Task<IActionResult> AddPlaybackEvent2([FromForm] Playback model)
{
Playback @event;
try
{
@event = new Playback();
@event.Video_Name = model.Video_Name;
@event.Video_Duration = model.Video_Duration;
@event.Playback_User = model.Playback_User;
@event.Playback_Duration = model.Playback_Duration;
_db.Playbacks.Add(@event);
_db.SaveChanges();
}
catch (Exception e)
{
return BadRequest(e.Message);
}
return Ok(@event);
}
Checked in MS SQL - Primary key and identity increment for Id column is configured.
CodePudding user response:
Adding this attribut to your Model. You need to set up this in your model if you using Code first approach
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }