Entity Framework ApplicationUser child entities return null

asp.net-core asp.net-core-mvc asp.net-identity-3 entity-framework-core


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
    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)

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

            entity.Property(e => e.DeviceName)

            entity.Property(e => e.UserId)

            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?

1/4/2016 2:18:43 AM

Accepted Answer

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

1/4/2016 2:47:47 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow