Home > Net >  FK collection returned by EF is null, but validation for duplicates, confirms thats, the collection
FK collection returned by EF is null, but validation for duplicates, confirms thats, the collection

Time:01-12

I'm trying to get a data of all the user drone's, but ef core returning empty collection.

public class User : AuditableEntity
   {
       public Guid Id { get; set; }
       public string Name { get; set; }
       public string Email { get; set; }
       public string UserData { get; set; }
       public bool IsActive { get; set; }
       public bool IsAdmin { get; set; }
       public DateTime LastActivity { get; set; }
       public IEnumerable<Drone> Drones { get; set; }
   }
public class Drone : AuditableEntity
   {
       public Guid Id { get; set; }
       public string CustomName { get; set; }
       public string Model { get; set; }
       public int Serial { get; set; }       
       public bool IsActive { get; set; }
       public string DroneData { get; set; }
       public virtual User User { get; set; }
   }

and user.Drones always has null value and i can't get and show the data, but this line of validation code

if (user.Drones.Contains(drone))
                    return ("This drone has been alredy registred", false);

shows me that, the user.Drones contains values. Why i should do, to get user.Drones collection?

CodePudding user response:

Ef uses a lazy loading, to load child instances you have to use Include

var user = context.Users.Where (i=> i.Id==userId)
.Include(i=>i.Drones)
.FirstOrDefault();

//or if you want just drones

var userDrones=context.Users.Where (i=> i.Id==userId)
.Select(i=>i.Drones)
.FirstOrDefault();

but it is better to add a foreign key UserId to Drone explicitly

public class Drone : AuditableEntity
   {
       public Guid Id { get; set; }
       .....

      public Guid UserId { get; set; }
       public virtual User User { get; set; }
   }

and use this query

var userDrones=context.Drones.Where (i=> i.UserId==userId).ToList();
  •  Tags:  
  • Related