c# - 在 ASP.Net Identity 2.0 UserManager.Users.ToListAsync 和 UserManager.FindByIdAsync 上包含属性

标签 c# asp.net asp.net-mvc entity-framework asp.net-identity-2

我正在尝试实现 Asp.Net Identity 2.0。到目前为止,我在 this blog 的帮助下管理得很好.但我走了一条稍微不同的路。我希望某些数据不属于 User 对象,而是属于新创建的 Customer 对象。我想将身份验证和授权数据与我的业务数据分开。

所以在我的例子中,我通过添加客户属性修改了 ApplicationUser 类:

    public Customer Customer { get; set; }

客户类如下所示:

public class Customer
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Insertion { get; set; }
    public Gender Gender { get; set; }
    public DateTime Birthdate { get; set; }
    ...etc.
    public virtual ApplicationUser User { get; set; }
}

我还在 ApplicationDbContext 中添加了关系:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Customer>()
            .HasRequired(u => u.User);
        base.OnModelCreating(modelBuilder);

    }

现在,在对注册 View 模型和 Controller 进行一些修改后,我可以注册为用户,并在 AspNetUsers 表中创建用户记录,并在客户表中创建客户记录,并引用用户记录。到目前为止一切顺利。

但是现在,当我出于显示目的检索用户时,Customer 属性为空。这是有道理的,因为未加载基础记录。通常我会使用 .Include 关键字来加载相关记录。但是我不知道在使用 Asp.Net identity 2.0 附带的默认 UserManager 时该怎么做。

有人知道如何实现吗?

最佳答案

我找到了答案。 Probablu 在回答之前需要更多的搜索。答案基于此SO Question中的答案。

我添加了一个名为 ApplicationUserStore 的类。

public class ApplicationUserStore : UserStore<ApplicationUser>
{
    public ApplicationUserStore(DbContext context)
        : base(context)
    {
    }

    public override System.Threading.Tasks.Task<ApplicationUser> FindByIdAsync(string userId)
    {

        return Users.Include(u=>u.Customer).Include(u => u.Roles).Include(u => u.Claims).Include(u => u.Logins).FirstOrDefaultAsync(u => u.Id == userId);
    }
}

在这个类中,我重写了 FindByIdAsync 以包含客户记录。

然后我在 IdentityConfig.cs 中更改了返回 ApplicationUserManager 的方法 Create 的第一行,以便它传递新创建的 ApplicationUserStore 而不是 UserStore。

var manager = new ApplicationUserManager(new ApplicationUserStore(context.Get<ApplicationDbContext>()));

我可能还必须覆盖其他一些获取方法以包含客户记录。

关于c# - 在 ASP.Net Identity 2.0 UserManager.Users.ToListAsync 和 UserManager.FindByIdAsync 上包含属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27039407/

相关文章:

c# - 将 Base64 值转换为数字

asp.net - 从ASP.Net中的文件播放音频

asp.net-mvc - Asp.NET MVC 2 预览 2 : Area's aspx namespace problem

c# - Stylecop 自定义规则不显示在设置中

c# - 使用EF4仅获得SQL表的最后一行的最有效方法是什么?

html - Gridview 宽度和对齐方式

asp.net - 无法找到或加载已注册的.Net Framework 数据提供程序

c# - 如何在没有 Controller 的情况下手动提供 .cshtml 文件?

asp.net - 使用 ASP.NET MVC 6 在 Web.config 中设置 IIS 设置

将 DataRow 转换为 T 类型时,C# Int64Converter 无法从 System.Int64 错误转换