6

我将 ASP.NET Identity 2.2.0 与 ASP.NET MVC 5.2.3 和 Entity Framework 6.1.2 一起使用。

我使用带有 Code First 的 ASP.NET Identity 向我的数据库添加了一个新属性及其对应的表,如下所示:

public class ApplicationUser
{
  [ForeignKey("UserTypeId")]
  public UserType Type { get; set;}
  public int UserTypeId { get; set;} 
}

public class UserType
{
  [Key]
  public int Id { get; set;}

  public string Name { get; set; }
}

现在,通过一些行动,当我打电话时:

var user = UserManager.FindByNameAsync(userName);

它确实为用户提供了正确的信息UserTypeId,因为这是一个原语,但它没有获得类的UserType属性ApplicationUser

如果我不使用此抽象,我将调用Entity Framework 中LoadProperty<T>的方法或方法以在类中包含名为(类型)的导航属性或关系。IncludeTypeUserTypeApplicationUser

我如何使用 ASP.NET Identity 来做到这一点UserManager?我怀疑唯一的方法是在我的自定义UserManager派生类中覆盖这个方法并自己做?

4

1 回答 1

5

使用实体框架延迟加载,您需要确保您的导航属性标记为virtual.

public class ApplicationUser
{
    [ForeignKey("UserTypeId")]
    public virtual UserType Type { get; set;}
    public int UserTypeId { get; set;} 
}

或者,如果您无法/不想使用延迟加载,那么您仍然可以像使用任何其他实体一样使用您的上下文:

var user = context.Users.Include(u => u.Type).Single(u => u.UserName == userName);
于 2015-08-13T20:22:47.930 回答