I have created a custom class called Person
to store name, address, etc. This class/model is cross-referenced from other models, including ApplicationUser
:
public class ApplicationUser : IdentityUser
{
public Person Person { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
In one of my controllers, I use the following code to get the current user logged in and get it's Person
object, like so:
var user = UserManager.FindById(User.Identity.GetUserId());
var person = user.Person;
My Person
class is also defined in the ApplicationDbContext
:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("MyContext", throwIfV1Schema: false)
{
}
public DbSet<Person> People { get; set; }
}
When I inspect user
, I can see that Entity Framework populated the object, because I see the user ID, email address, password hash, everything! Everything except the Person
property! However, I can see in the database that the corresponding row is not null
, but has the correct ID for the Person
.
I'm new to ASP.NET/MVC/Entity framework and I've read that it uses lazy loading by default. Is this what I'm experiencing? If so, how do I tell Entity to use eager loading on the Person
property? If not, what am I doing wrong?
Person
property in methodUserManager.FindById
...IDbSet<Person>
to theApplicationDbContext
? & 2) Try marking the ApplicationUser.Person property as virtual (so the proxy class can lazy-load it). -- It sounds to me like the DB doesn't know it exists as a relationship and may need to use implicit conventions/attributes/fluent model binding to tell EF about it.ApplicationDbContext
. 2) I'll try marking it as virtual.