EF7 Identity not loading User extended properties

1.5k views Asked by At

I have an extended IdentityUser class which contains a reference to another entity on my DB, but whenever I try to get the User with the UserManager, the referenced entity always comes empty:

My implementation of the User class

public class Usuario : IdentityUser
{
    public int ClienteID { get; set; }
    public virtual Cliente Cliente { get; set; }
}

A controller that uses the referenced property on the user

[Authorize]
[HttpGet]
public async Task<Direccion> GET()
{
    var usuario = await UserManager.FindByNameAsync(Context.User.Identity.Name);
    // Cliente will always be null
    return usuario.Cliente.Direccion;
}

I also tried removing the virtual keyword from the reference, so that it is lazy loaded, but I'm not sure that is already implemented on EF7.

Any ideas on how to achieve this?

1

There are 1 answers

1
big_water On

I had this issue as well and solved it with the help of the EF Core Documentation. You need to use the Include method to get the related data to populate. In my case:

Entity Class:

public class ServiceEntity
{
    public int ServiceId { get; set; }
    public int ServiceTypeId { get; set; }

    public virtual ServiceTypeEntity ServiceType { get; set; } 
     
}

Accessing my DbContext object:

public ServiceEntity GetById(int id)
{
    var service = this.DbClient.Services.Include(s => s.ServiceType).Where(c => c.ServiceId == id).FirstOrDefault();

    return service;
}

I had to make the property "virtual" as well. My understanding is EF Core needs to be able to override the properties of the related object in order to populate the values.

Also, as of this post date, EF Core does not yet support Lazy Loading, only Eager Loading and Explicit Loading.

Hope this helps!