❔ Why and when does todoId property get updated i.e. its different between prints to console.

[HttpPost]
public async Task<ActionResult<TodoItem>> PostTodoItem(TodoPostDto todoItem)
{
if (_context.TodoItems == null)
{
return Problem("Entity set 'TodoContext.TodoItems' is null.");
}

TodoItem todo = new TodoItem { IsComplete = todoItem.IsComplete, Name = todoItem.Name };

Console.WriteLine(todo.Id);
TodoItem addedTodo = _context.TodoItems.Add(todo).Entity;
await _context.SaveChangesAsync();
Console.WriteLine(todo.Id);

return CreatedAtAction(nameof(GetTodoItem), new { id = todo.Id }, addedTodo);
}
[HttpPost]
public async Task<ActionResult<TodoItem>> PostTodoItem(TodoPostDto todoItem)
{
if (_context.TodoItems == null)
{
return Problem("Entity set 'TodoContext.TodoItems' is null.");
}

TodoItem todo = new TodoItem { IsComplete = todoItem.IsComplete, Name = todoItem.Name };

Console.WriteLine(todo.Id);
TodoItem addedTodo = _context.TodoItems.Add(todo).Entity;
await _context.SaveChangesAsync();
Console.WriteLine(todo.Id);

return CreatedAtAction(nameof(GetTodoItem), new { id = todo.Id }, addedTodo);
}
2 Replies
Anton
Anton3y ago
it's likely because id is generated by the db in SaveChangesAsync and returned back to you and assigned
Accord
Accord3y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.

Did you find this page helpful?