简体   繁体   中英

Unable to populate an ICollection with related data in Entity Framework

I have tables with created using below models in Entity Framework

public class User
{
    public int Id{ get; set; }
    public string Name { get; set; }       
    public bool IsActive { get; set; }
    public ICollection<AssigneeMonth> AssigneeMonths { get; set; }
}

public class AssigneeMonth
{
    public int Id { get; set; }
    public int AssigneeId { get; set; }
    public Month Month { get; set; }
    public User Assignee { get; set; }
}

public class ProjectAssignee
{
    public int Id { get; set; }
    public int ProjectId { get; set; }
    public int AssigneeId { get; set; }

    public bool IsActive { get; set; }
    public AutomationProject Project { get; set; }

    [ForeignKey("AssigneeId")]
    public User User { get; set; }
}

I am trying to get data into the collection AssigneeMonths from AssigneeMonth using this code:

 var assn = dataContext.ProjectAssignees
                       .Where(r => r.Project.Name == project.Name && r.IsActive)
                       .Include(u => u.User)
                       .ToList();

But AssigneeMonths collection in the above assn is always null even if I have data in AssigneeMonth for the user

May I know what's wrong with the above code?

Since you're using eager loading, you're only loading the information for user, not its navigational properties.

You can use the code in this answer , which applied to your case will look like this:

var assn = dataContext.ProjectAssignees
                   .Where(r => r.Project.Name == project.Name && r.IsActive)
                   .Include(u => u.User.SelectMany(u => u.AssigneeMonths))
                   .ToList();

Since AssigneeMonths is a collection, you need to use SelectMany instead of Select.

Other option would be to do it like this (as posted in other answers in that link):

var assn = dataContext.ProjectAssignees
                   .Where(r => r.Project.Name == project.Name && r.IsActive)
                   .Include(u => u.User)
                   .Include("User.AssigneeMonths")
                   .ToList();

But I personally don't like the second method because its easy to make mistakes with the string and it will hide the errors until runtime.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM