当我们可以使用应用程序 dbcontext 时,为什么我们使用 UserManager 来访问用户配置文件信息?

Why do we use UserManager to acess user profile info when we can use application dbcontext?

当我在谷歌上搜索如何找到 UserProfile 属性时,我得到了结果,所有结果都使用 UserManager 来访问 UserProfile 自定义属性。

所以如果我有自定义 ApplicationUser

public class ApplicationUser : IdentityUser
    {
        public int AccType { get; set; } // 
    }

在我的控制器中,简化代码看起来像

ApplicationUser usr = _context.Users.SingleOrDefault(u => u.UserName == User.Identity.Name);

此方法将 UserProfile 属性公开给代码。那么为什么每个人都使用 UserManager???

UserManager 包括特定于通常为用户执行的任务的验证规则和辅助方法,例如使用安全密码创建新用户、验证输入的密码、adding/removing 从角色等

是的,您可以直接使用 ApplicationDbContext,但是您需要针对 DbSet<ApplicationUIser> 编写查询,而 UserManager 已经有了这些查询,并进行了验证 - 以及更多.

例如,UserManager.FindByNameAsync已经定义,另外它在执行搜索之前规范化名称。

看看 source,看看 UserManagerDbSet<ApplicationUser> 提供什么。