ASP.NET 核心身份用户关系

ASP.NET Core IdentityUser relations

如何将相关对象添加到数据库中?

我的身份用户:

public class ApplicationUser : IdentityUser
{
    public ICollection<Todo> Todos { get; set; }
}

我的 Todo 模型:

public class Todo 
{
   public int Id { get; set; }
   public string Name { get; set; }
   public ApplicationUser User { get; set; }
}

我有一个类似 /api/todos 的 WebAPI。

[HttpPost]
public async Task<IActionResult> Post([FromBody]string name)
{
   var user = await _userManager.GetUserAsync(User);
   // _db is IdentityDbContext that I use
   var newTodo = new Todo() { Name = "do the laundry" }; // Do I have to specify the user like User = user?
   _db.Todos.Add(newTodo);
   await _db.SaveChangesAsync();
   return CreatedAt(...);
}

问题:我做的对吗?我必须将用户传递给新的待办事项吗?

我能以某种方式添加这样的待办事项吗?:

user.Todos.Add(newTodo);

但是我该如何保存呢?

添加用户:

var user = await _userManager.GetUserAsync(User);
var newTodo = new Todo() { Name = "do the laundry", User = user };
_db.Todos.Add(newTodo);
await _db.SaveChangesAsync();

或添加到用户并更新:

var user = await _userManager.GetUserAsync(User);
var newTodo = new Todo() { Name = "do the laundry" };
user.Todos.Add(newTodo);
_db.Users.Update(user);
await _db.SaveChangesAsync();

任何一种方式都应该没问题。