【问题标题】:Unable to populate an ICollection with related data in Entity Framework无法使用实体框架中的相关数据填充 ICollection
【发布时间】:2018-02-09 02:06:28
【问题描述】:

我在实体框架中使用以下模型创建了表

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; }
}

我正在尝试使用以下代码将数据从 AssigneeMonth 获取到集合 AssigneeMonths

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

但是上面assn 中的AssigneeMonths 集合始终为空,即使我在AssigneeMonth 中有用户的数据

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

【问题讨论】:

    标签: c# entity-framework


    【解决方案1】:

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

    您可以使用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();
    

    但我个人不喜欢第二种方法,因为它容易对字符串出错,并且会隐藏错误直到运行时。

    【讨论】:

    • 其实只支持Select
    • Select 应该可以工作,但我现在无法测试它。我确定SelectMany 有效,但也许用例不同。我稍后再看看。
    猜你喜欢
    • 2011-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-11
    • 1970-01-01
    • 2020-07-20
    • 1970-01-01
    相关资源
    最近更新 更多