简体   繁体   English

无法使用实体框架中的相关数据填充ICollection

[英]Unable to populate an ICollection with related data in Entity Framework

I have tables with created using below models in Entity Framework 我在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: 我正在尝试使用以下代码将数据从AssigneeMonth放入集合AssigneeMonths

 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 但是即使我的用户在AssigneeMonth有数据,上述assn中的AssigneeMonths集合也始终为null

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. 由于AssigneeMonths是一个集合,因此您需要使用SelectMany而不是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. 但是我个人不喜欢第二种方法,因为第二种方法很容易在字符串上出错,并且会一直隐藏错误直到运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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