【问题标题】:Entity Framework 6: Load related entities with null or blank foreign key实体框架 6:使用空或空白外键加载相关实体
【发布时间】:2015-01-08 02:25:44
【问题描述】:

Parent 有一个 Child 的集合。 子项对父项 (ParentID) 有一个外键,但该外键可能为空/空白。 我希望实体框架始终为所有父项加载具有空/空白外键的子项。

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

【问题讨论】:

    标签: c# .net entity-framework entity-framework-6


    【解决方案1】:

    没有 ParentId,孩子就是所谓的orphan。如果没有填充的外键属性,就无法将子级链接到父级。

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

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

    【讨论】:

    • 有没有办法将它附加到 Parent 中的属性上?或者以某种方式告诉 EntityFramework,对于“孩子”,它应该使用该查询?
    • @hatcyl 不是自动的。您需要在 ParentFactory 中运行上面的代码并将其作为单独的属性附加到 Parent,或者执行一些看起来更像 Active Record 模式的操作,并更新 DbContext 的实例以及Parent 类,并在 Parent 的构造函数中运行上面的代码。无论哪种方式,您都不能将孤儿添加到 Children 集合中。你需要一个单独的属性。
    猜你喜欢
    • 2014-10-23
    • 1970-01-01
    • 1970-01-01
    • 2018-07-04
    • 2011-04-09
    • 2016-09-07
    • 1970-01-01
    • 2012-02-07
    • 1970-01-01
    相关资源
    最近更新 更多