text
stringlengths
0
13.4k
item can "remember" the user that owns it:
Models/TodoItem.cs
public string UserId { get; set; }
Since you updated the entity model used by the database context, you
also need to migrate the database. Create a new migration using dotnet
ef in the terminal:
dotnet ef migrations add AddItemUserId
81
Using identity in the application
This creates a new migration called AddItemUserId which will add a new
column to the Items table, mirroring the change you made to the
TodoItem model.
Use dotnet ef again to apply it to the database:
dotnet ef database update
Update the service class
With the database and the database context updated, you can now
update the GetIncompleteItemsAsync() method in the TodoItemService
and add another clause to the Where statement:
Services/TodoItemService.cs
public async Task<TodoItem[]> GetIncompleteItemsAsync(
ApplicationUser user)
{
return await _context.Items
.Where(x => x.IsDone == false && x.UserId == user.Id)
.ToArrayAsync();
}
If you run the application and register or log in, you'll see an empty to-do
list once again. Unfortunately, any items you try to add disappear into
the ether, because you haven't updated the AddItem action to be user-
aware yet.
Update the AddItem and MarkDone actions
You'll need to use the UserManager to get the current user in the
AddItem and MarkDone action methods, just like you did in Index .
Here are both updated methods:
82
Using identity in the application
Controllers/TodoController.cs
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddItem(TodoItem newItem)
{
if (!ModelState.IsValid)
{
return RedirectToAction("Index");
}
var currentUser = await _userManager.GetUserAsync(User);
if (currentUser == null) return Challenge();
var successful = await _todoItemService
.AddItemAsync(newItem, currentUser);
if (!successful)
{