2017-02-17 53 views
1

我有一個簡單的沙箱項目,我用它來更好地理解.net Core Identity的工作方式,我遇到了一些不一致的地方,我希望有人能解釋。該項目正在使用實體框架。身份角色沒有被填充

我用這個真棒文章幫我設置了項目,https://medium.com/@goodealsnow/asp-net-core-identity-3-0-6018fc151b4#.2env44446和我的User類如下。

public class User : IdentityUser<int> 
{ 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    public string TempPassword { get; set; } 
} 

我播種的分貝有三個用戶和三個角色,一個用戶對於每個角色,「所有者」,「管理」和「用戶」。我加了一些政策,爲我的行爲,

auth.AddPolicy("Owner", policy => 
{ 
    policy.RequireAuthenticatedUser(); 
    policy.RequireRole("Owner"); 
}); 

auth.AddPolicy("Admin", policy => 
{ 
    policy.RequireAuthenticatedUser(); 
    policy.RequireRole("Admin", "Owner"); 
}); 

auth.AddPolicy("User", policy => 
{ 
    policy.RequireAuthenticatedUser(); 
}); 

那麼喜歡[Authorize("Admin")]工作我的屬性很棒。我甚至增加了一些主要的擴展爲使

public static class PrincipalExtensions 
{ 
    public static bool IsOwner(this ClaimsPrincipal principal) 
    { 
     return principal.IsInRole("Owner"); 
    } 

    public static bool IsAdmin(this ClaimsPrincipal principal) 
    { 
     return principal.IsInRole("Admin") || principal.IsInRole("Owner"); 
    } 

    public static bool IsUser(this ClaimsPrincipal principal) 
    { 
     return principal.Identity.IsAuthenticated; 
    } 
} 

所以我可以做if(User.IsAdmin())這完美的作品也是如此。

這裏是會很奇怪......

如果我通過下面的代碼,我得到混淆的結果步驟。

var user = await _userManager.GetUserAsync(User);    
var userRoles = await _userManager.GetRolesAsync(user); 
await _userManager.AddToRoleAsync(user, "Owner"); 

第一行爲我提供了一個User對象。在該對象上有一個他的角色集合user.Roles,但即使用戶確實有有角色,它也會顯示爲空(Count = 0)。

第二行獲取用戶的Roles,並且它填充正確。

第三行爲用戶添加了「所有者」角色,並且它可以正常工作(數據庫已更新),而且本地變量user突然在user.Roles中擁有該角色!請注意,用戶的其他角色都不會出現,只有那一個。

所以我基本上有兩個問題:1。爲什麼不user對象已在user.Roles填充到開始? 2.爲什麼添加角色後突然同步?

任何幫助表示讚賞。

回答

1

由於EntityFramework Identity UserStore未請求信息,致電GetUserAsync()後,您的Roles集合未填充。它的作用相當於直接通過您的DbContext訪問用戶數據,並且不需要致電Include()

現在EF Core does not support lazy loading,因此user.Roles導航屬性不會自動填充。是的,這使得此刻的行爲有點虛僞。

在您撥打GetRolesAsync()AddToRoleAsync()時,您正在爲您顯式填充數據,因爲您正在直接操作角色。

+0

感謝您的鏈接。起初,我只是想說「如果他們不打算填充它,他們爲什麼要把它放在對象上」,但是在該頁面的積壓部分中,它表示它即將到來。 – nurdyguy

+0

嘿,最重要的是,'用戶。Roles'是隻讀的,所以我甚至不能自己填充它! – nurdyguy