6

I am using ASP.NET Identity 2.2.0 with ASP.NET MVC 5.2.3 and Entity Framework 6.1.2.

I added a new property and its corresponding table to my database using ASP.NET Identity with Code First like so:

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; }
}

Now, from some action, when I call:

var user = UserManager.FindByNameAsync(userName);

It does get the user with the correct UserTypeId because that is a primitive, but it does not get the UserType property of the ApplicationUser class.

If I were not using this abstraction, I would either call LoadProperty<T> or the Include method in Entity Framework to include the navigational property or relation named Type (of type UserType) on the ApplicationUser class.

How do I do that with ASP.NET Identity's UserManager? I suspect the only way would be to override this method in my custom UserManager derived class and do it myself?

Water Cooler v2
  • 29,006
  • 41
  • 139
  • 286

1 Answers1

5

With Entity Framework lazy loading, you need to ensure that your navigation properties are marked as virtual.

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

Alternatively if you are unable/don't want to use lazy loading, then you can still use your context as you would any other entity:

var user = context.Users.Include(u => u.Type).Single(u => u.UserName == userName);
DavidG
  • 95,392
  • 10
  • 185
  • 181
  • 2
    this does not apply anymore to Entity Framework Core. Lazy loading is disabled no matter if you use `virtual`. https://docs.efproject.net/en/latest/querying/related-data.html#lazy-loading – diegosasw Sep 16 '16 at 03:33
  • @iberodev Well this question isn't tagged with EF Core so that's not an issue. In fact EF Core doesn't even support lazy loading yet, though it is on the roadmap, expect it to work in the next major release. – DavidG Sep 16 '16 at 07:55
  • Perhaps overriding the user store users to include custom child entities will work, cases like one to many without navigationId column on the users table – Jay Oct 02 '17 at 03:04