How to tell UserManager.FindByNameAsync to include a relationship?

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 the ASP.NET identifier with First code, for example:

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 gets the user with the correct UserTypeId because it is a primitive, but it does not get the UserType property of the ApplicationUser class.

If I had not used this abstraction, I would have called the LoadProperty<T> or Include method in the Entity Framework to include a navigation property or relationship named Type (of type UserType ) in the ApplicationUser class.

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

+4
source share
1 answer

When deferred loading the Entity Framework, you need to make sure 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 cannot / do not want to use delayed loading, you can still use your context, like any other object:

 var user = context.Users.Include(u => u.Type).Single(u => u.UserName == userName); 
+5
source

All Articles