簡體   English   中英

ASP.NET MVC 5 Identity userManager.IsInRole

[英]ASP.NET MVC 5 Identity userManager.IsInRole

以下代碼不起作用,我無法解釋為什么...我的用戶管理器造成了很大的困擾,因為它創建用戶和角色就好了但是當我運行此代碼時userManager.IsInRole總是返回false,所以第二個時間我運行我的種子我遇到了錯誤,因為它試圖創建記錄,盡管它已經存在!

請注意,這是在我針對遷移項目運行update-database時發生的,事實上這是一個導致問題的非ASP項目,如果是這樣,為什么呢? 不應該拋出錯誤。

這是我使用Identity的第一個項目,雖然它的工作原理似乎很好,很少有最新的高質量文檔,所以如果有任何人有這方面的資料我將不勝感激。

    public void Run(BlogContext blogContext)
    {
        var userStore = new UserStore<User>((BlogContext) blogContext);
        var userManager = new UserManager<User>(userStore);

        var userRoles = new List<UserRole>()
        {
            new UserRole() {Username = "SysAdmin@test.com", Role = "SysAdmin"},
            new UserRole() {Username = "testAdmin@test.com", Role = "Admin"},
            new UserRole() {Username = "testAuthor@test.com", Role = "Author"}
        };

        foreach (var userRole in userRoles)
        {
            var userId = userManager.FindByName(userRole.Username).Id;

            if (!userManager.IsInRole(userId, userRole.Role))
                userManager.AddToRole(userId, userRole.Role);
        }


        blogContext.SaveChanges();
    }

因此,我將自己回答這個問題,以拯救任何人因此而遭受的痛苦。

出現這種情況的原因是我禁用了延遲加載,我已經在我的遷移項目中啟用了這個,就像這樣。

protected override void Seed(BlogContext blogContext)
    {
        AutomaticMigrationsEnabled = true;
        blogContext.Configuration.LazyLoadingEnabled = true;
        //Add seed classes here!    
    }

暫無
暫無

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

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