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?
Lazy loading doesn't work on EF7
. But You can use Include
in your request.