如何将相关对象添加到数据库?
我的IdentityUser:
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(...);
}
问题:我做得对吗?我是否必须将用户传递给新的Todo项目?
我能以某种方式添加这样的待办事项吗?:
user.Todos.Add(newTodo);
但我该怎么保存呢?
答案 0 :(得分:2)
添加用户:
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();
无论哪种方式都应该没问题。