Entity Framework 6:使用空或空白外键加载相关实体

Entity Framework 6: Load related entities with null or blank foreign key

Parent 有 Child 的集合。 子项有一个到父项的外键 (ParentID),但该外键可能为空/空白。 我希望 Entity Framework 始终为所有父级加载带有空/空白外键的子级。

public class Parent
{
    public string ID { get; set; }
    public virtual ICollection<Child> Children { get; set; } //Should load it's children AND children without foreign key.
}

public class Child
{
    public string ID { get; set; }
    public string ParentID { get; set; } //This can be null / blank.
}

没有 ParentId,child 就是所谓的 orphan。没有填充的外键 属性.

就无法 link a child 到 parent

如果您只是想在 Children 中查询具有 null 或空 ParentId 的记录,请对 DbContext 执行类似以下操作:

var orphans = myContext.Children.Where(child => String.IsNullOrEmpty(child.ParentId));