无法使用Entity Framework中的相关数据填充ICollection

时间:2018-02-08 17:02:47

标签: c# 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; }
}

我正在尝试使用以下代码从AssigneeMonths将数据导入集合AssigneeMonth

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

但即使我在AssigneeMonths中为用户提供了数据,上述assn中的AssigneeMonth集合也始终为空

我可以知道上面代码有什么问题吗?

1 个答案:

答案 0 :(得分:0)

由于您正在使用预先加载,因此您只是为用户加载信息,而不是其导航属性。

您可以使用this answer中的代码,适用于您的案例的代码如下所示:

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

由于AssigneeMonths是一个集合,您需要使用SelectMany而不是Select。

其他选择是这样做(在该链接的其他答案中公布):

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

但是我个人不喜欢第二种方法,因为它很容易在字符串中出错,它会在运行时隐藏错误。