Dashsa
Dashsa

Reputation: 718

child collection not populating with more than 1 result

I have a model that has a child collection that is only returning the first record. the parent (userModel) looks like:

 public class User
{

    [Key]
    public int UserID { get; set; }
    public string Username { get; set; }
    [StringLength(50)]
    public string EmailAddress { get; set; }
    public bool IsDeleted{ get; set; }
    [ForeignKey("UserID")]
    public virtual UserInformation UserInformation{ get; set; }
    [ForeignKey("UserID")]
    public virtual IEnumerable<UserMember> UserMember{ get; set; }

}

The model that is not hydrating correctly is the UserMember collection. It looks like this:

 public class UserMember
{
    [Key]
    public int UserID { get; set; }
    public int GroupID { get; set; }
    public DateTimeOffset Created { get; set; }
    public virtual Group Group { get; set; }
}

The query that I am using is:

public IQueryable<User> GetUserByUserSId(Guid userSid)
    {
        return _freightPortalPreferencesContext.User
                .Include(ui => ui.UserInformation)
                .Include(um => um.UserMember)
                .Where(x => x.SID == userSid && x.Enabled);

    }

It is hydrating one UserMember, but I am expecting to see 3 results. User--> UserMember.

I have tried changing the IEnumerable to be a ICollection and it also doesn't work. I dont have any fluid syntax code in the context, apart from the usual mapping etc - modelBuilder.Entity().ToTable("user", "info");

Any ideas?

Upvotes: 0

Views: 184

Answers (1)

TanvirArjel
TanvirArjel

Reputation: 32059

You didn't map your foreign keys correctly. Your model classes should be as follows:

public class User
{

    [Key]
    public int UserID { get; set; }
    public string Username { get; set; }
    [StringLength(50)]
    public string EmailAddress { get; set; }
    public bool IsDeleted{ get; set; }

    public virtual UserInformation UserInformation{ get; set; }

    public virtual ICollection<UserMember> UserMembers { get; set; }

}

public class UserMember
{
    [Key]
    [ForeignKey("User")]
    public int UserID { get; set; }
    public int GroupID { get; set; }
    public DateTimeOffset Created { get; set; }
    public virtual Group Group { get; set; }

    public virtual User User {get; set;}
}

Then your query should be as follows:

public IQueryable<User> GetUserByUserSId(Guid userId)
{
        return _freightPortalPreferencesContext.User
                .Include(u => u.UserInformation)
                .Include(u => u.UserMembers)
                .Where(u => u.SID == userId && u.Enabled).AsQueryable();

}

Upvotes: 1

Related Questions