簡體   English   中英

如何獲得基於屬性的所有具有ASP.NET Identity的用戶?

[英]How can I get all users with ASP.NET Identity based on a property?

我嘗試了一些非常簡單的方法,但是由於某種原因它無法正常工作,因此,我在這里查看是否有任何方法可以使我有所啟發,並且在其他地方找不到示例或解決方案(Bing / google)

問題非常簡單,我使用的是經過稍微修改的ApplicationUser類:

 public class ApplicationUser : IdentityUser
{
    public virtual Guid BusinessId { get; set; }
}

使用以下幫助程序(擴展方法):

public static Guid GetBusinessId(this IIdentity user)
    {
         var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
         var currentUser = manager.FindById(user.GetUserId());

        return currentUser.BusinessId;
    }

然后最后是“導致”問題的方法:

public IQueryable<ApplicationUser> Get()
    {
        var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));

        Guid businessId = this.User.Identity.GetBusinessId();
        var users = userManager.Users.Where(u => u.BusinessId == businessId);

        return users;
    }

這里發生的是,當我查詢用戶時,我什么也沒得到,但是它至少應該獲得當前登錄的用戶,因為他具有正確的businessId。

如果我在用戶查詢上設置一個斷點,並在立即窗口上嘗試諸如“ ToList()”或“ ToList()[0]”之類的操作,則會得到以下結果:

?users.ToList()
Count = 1
[0]: Could not evaluate expression
?users.ToList()[0]
An internal error has occurred while evaluating method System.Collections.Generic.List`1[T].get_Item().

有什么想法為什么?或者是否有“正確”的方法?

謝謝

在這里看看如何從ASP.NET Identity獲取用戶列表? 從答案中退出

我發現我沒有使用派生的ApplicationUser對象,所以我繼續將它的所有用法更改為普通的舊User。 然后,我只是為以下內容更改了ApplicationDbContext定義:

 public class ApplicationDbContext : IdentityDbContext< User, UserClaim, UserSecret, UserLogin, Role, UserRole, Token, UserManagement> { } 

現在,我可以訪問用戶列表:

 UsersContext = new ApplicationDbContext();
 ...
 UsersContext.Users.ToList();

但是,我認為將來會再次出現並困擾我(我可能需要向User添加更多字段),所以我可能必須使用與此問題相同的方法:

獲取ASP.NET MVC5身份系統中的所有角色名稱

編輯:由於我需要添加一個新的屬性,所以我必須還原所做的更改。 因此,我繼續與ASP.NET Identity Sample Project進行了逐行比較,發現生成的項目具有以下內容:

IdentityManager = new AuthenticationIdentityManager(new IdentityStore());

而Sample應用程序已將數據庫上下文包含在構造函數中。 所以我在構造函數中添加了它,重新創建了數據庫,問題就消失了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM