我正在尝试实现 Asp.Net Identity 2.0。到目前为止,在以下人员的帮助下我做得很好这个博客 http://typecastexception.com/post/2014/06/22/ASPNET-Identity-20-Customizing-Users-and-Roles.aspx。但我走了一条稍微不同的路。我希望某些数据不是 User 对象的一部分,而是新创建的 Customer 对象的一部分。我希望将身份验证和授权数据与我的业务数据分开。
因此,就我而言,我通过添加客户属性来修改 ApplicationUser 类:
public Customer Customer { get; set; }
Customer 类如下所示:
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);
}
因此,现在对注册视图模型和控制器进行一些修改后,我可以注册为用户,并在 AspNetUsers 表中创建用户记录,并在 Customer 表中创建一条引用用户记录的客户记录。到目前为止,一切都很好。
但现在,当我检索用户(例如出于显示目的)时,Customer 属性为空。这是有道理的,因为基础记录未加载。通常我会使用 .include 关键字来加载相关记录。但我不知道在使用 Asp.Net Identity 2.0 附带的默认 UserManager 时如何做到这一点。
有人知道如何实现这一目标吗?
我找到了答案。在回答之前可能需要更多搜索。答案是基于这个答案那么问题 https://stackoverflow.com/questions/26646939/custom-entities-with-asp-net-identity-one-to-many
我添加了一个名为 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 中更改了 Create 方法中的第一行,该方法返回 ApplicationUserManager,以便它传递新创建的 ApplicationUserStore 而不是 UserStore。
var manager = new ApplicationUserManager(new ApplicationUserStore(context.Get<ApplicationDbContext>()));
我可能还必须覆盖其他一些获取方法以包含客户记录。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)