【问题标题】:How do I tell UserManager.FindByNameAsync to include a relation?如何告诉 UserManager.FindByNameAsync 包含关系?
【发布时间】:2015-11-06 23:22:07
【问题描述】:

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

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

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,因为这是一个原语,但它没有获得ApplicationUser 类的UserType 属性。

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

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

【问题讨论】:

  • 您是否尝试过将您的ApplicationUservirtualType 属性设为virtual
  • 谢谢。做到了。非常感谢。如果您将其发布为答案,好吗? :-)
  • 所以它无法代理它?

标签: entity-framework asp.net-identity asp.net-identity-3


【解决方案1】:

使用实体框架延迟加载,您需要确保将导航属性标记为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);

【讨论】:

  • 这不再适用于 Entity Framework Core。无论您是否使用virtual,都会禁用延迟加载。 docs.efproject.net/en/latest/querying/…
  • @iberodev 这个问题没有用 EF Core 标记,所以这不是问题。事实上,EF Core 甚至还不支持延迟加载,虽然它在路线图上,但预计它会在下一个主要版本中工作。
  • 也许覆盖用户存储用户以包含自定义子实体会起作用,例如一对多的情况,用户表上没有 navigationId 列
猜你喜欢
  • 2011-11-19
  • 1970-01-01
  • 1970-01-01
  • 2017-05-21
  • 2021-05-07
  • 1970-01-01
  • 2010-12-13
  • 2016-03-16
  • 2013-06-25
相关资源
最近更新 更多