2

We have an ApplicationUser class which inherits from IdentityUser. An ApplicationUser can have many devices.

    public class ApplicationUser : IdentityUser
{
    public virtual ICollection<Device> Devices { get; set; }
}

A Device is defined as

    public partial class Device
{
    [Key]
    public int DeviceID { get; set; }
    public string UserId { get; set; }
    public virtual ApplicationUser User { get; set; }
    public string DeviceName { get; set; }
}

The one-to-many relationship is set in

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

            modelBuilder.Entity<Device>(entity =>
        {
            entity.HasKey(e => e.DeviceID);

            entity.Property(e => e.DeviceName)
                .IsRequired()
                .HasMaxLength(50)
                .HasColumnType("varchar");

            entity.Property(e => e.UserId)
                .IsRequired()
                .HasMaxLength(450);

            entity.HasOne(d => d.User).WithMany(p => p.Devices).HasForeignKey(d => d.UserId).OnDelete(DeleteBehavior.Restrict);
        });

        public virtual DbSet<Device> Devices { get; set; }
}

The following code correctly returns the user

var membershipUser = await _userManager.FindByEmailAsync(email);

I know membershipUser has 6 devices in the Devices table, however the Devices property is null.

The following also returns null for this users devices

var deviceList = membershipUser.Devices.ToList();

How do I wire up Devices so they are correctly returned?

Vague
  • 2,198
  • 3
  • 18
  • 46

1 Answers1

3

Lazy loading doesn't work on EF7. But You can use Include in your request.

agua from mars
  • 16,428
  • 4
  • 61
  • 70
  • 1
    Thank you @aqua from mars. For others who might stumble on this issue here is the [link](https://github.com/aspnet/EntityFramework/issues/3797) to the issue tracker for lazy loading. – Vague Jan 04 '16 at 08:16
  • 2
    This is a totally correct answer, however not entirely helpful in the case of `ApplicationUser`, which is typically loaded with a call to `_userManager.FindByFoo(foo)` and does not support the `.Include` extension method like a normal EF query would. A more complete answer can be found here: http://stackoverflow.com/questions/30875569/ef7-identity-not-loading-user-extended-properties – Dave Smash Feb 23 '17 at 19:34