2016-07-26 25 views
1

有人可以幫我嗎?我想在Identity 3中實現編輯用戶的角色,但是當我寫這個,我有一個錯誤:「任務<PeopleUser>不包含角色和沒有擴展方法的定義」角色「接受Tasl類型的第一個參數<PeopleUser>

Task doesn't contain a definition for Roles and no extensions method "Roles" accepting a first argument of type Task

這裏是控制器代碼

public virtual ActionResult Edit(PeopleUser user, string role) 
{ 
    if (ModelState.IsValid) 
    { 
     var oldUser = _userManager.FindByIdAsync(user.Id); 
     var oldRoleId = oldUser.Roles.SingleOrDefault().RoleId; 
     var oldRoleName = _db.Roles.SingleOrDefault(r => r.Id == oldRoleId).Name; 

     if (oldRoleName != role) 
     { 
      _userManager.RemoveFromRoleAsync(user, oldRoleName); 
      _userManager.AddToRoleAsync(user, role); 
     } 
     _db.Entry(user).State = EntityState.Modified; 

     return RedirectToAction("Index", "Home"); 
    } 
    return View(user); 
} 
+0

什麼是.Net平臺,您使用的語句和程序集引用? –

+0

核心1與EF 7和身份3,使用Microsoft.AspNet.Authorization; 使用Microsoft.AspNet.Identity; 使用Microsoft.AspNet.Mvc;使用Microsoft.Data.Entity的 ;使用系統的 ;使用System.Linq的 ; using System.Threading.Tasks; 使用TraficC.Model; –

回答

1

您需要awaitTask之前,你可以使用TUser對象

。個
// Note that the signature has async and Task<ActionResult>. 
public virtual async Task<ActionResult> Edit(PeopleUser user, string role) 
{ 
    if (ModelState.IsValid) 
    { 
     var oldUser = await _userManager.FindByIdAsync(user.Id); // Note the await keyword. 
     var oldRoleId = oldUser.Roles.SingleOrDefault().RoleId; 
     var oldRoleName = _db.Roles.SingleOrDefault(r => r.Id == oldRoleId).Name; 

     if (oldRoleName != role) 
     { 
      // I've added await here as well... 
      await _userManager.RemoveFromRoleAsync(user, oldRoleName); 
      await _userManager.AddToRoleAsync(user, role); 
     } 
     _db.Entry(user).State = EntityState.Modified; 

     return RedirectToAction("Index", "Home"); 
    } 
    return View(user); 
} 

FindByIdAsync()回報Task<TUser>,這意味着你需要「解包」了,訪問TUser對象之前。您可以使用await關鍵字將其打開。

public virtual Task<TUser> FindByIdAsync(
    TKey userId 
) 

所以澄清你的例子:

// Create the task. Note the difference between the types of oldUserTask and oldUser. 
Task<User> oldUserTask = _userManager.FindByIdAsync(user.Id); 
// Await the task. 
User oldUser = await oldUserTask; 
// Now you can do something with oldUser. 
oldUser.DoStuff(); 

更多關於異步編程here

In .NET Framework programming, an async method typically returns a Task or a Task<TResult> . Inside an async method, an await operator is applied to a task that's returned from a call to another async method. You specify Task<TResult> as the return type if the method contains a return statement that specifies an operand of type TResult . You use Task as the return type if the method has no return statement or has a return statement that doesn't return an operand.

+0

非常感謝你,它的工作原理,但我有一些問題,因爲當我在用戶創建的角色中進行調試時,我看到null,但是在我編寫剃刀語法@ user.isinrole時的界面中......它可以工作並在表ASP中使用。 NetUsers出現 –

相關問題