[英]Entity Framework 6: Load related entities with null or blank foreign key
Parent has a collection of Child. 父母有一个孩子的集合。 Child has a Foreign Key to Parent (ParentID), but that foreign key might by null / blank. 子级具有父级外键(ParentID),但该外键可能为空/空白。 I want Entity Framework to always load Child with null / blank foreign key for all Parent. 我希望实体框架始终为所有父级加载具有空/空白外键的子级。
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.
}
Without a ParentId, the child is what's known as an orphan . 没有ParentId,孩子就是所谓的孤儿 。 There's no way to link a child to a parent without a populated foreign key property. 没有填充的外键属性,无法将孩子链接到父母。
If you're just looking to query the Children for records with a null or empty ParentId, do something like the following with your DbContext: 如果您只是想查询子项以获取具有空或空的ParentId的记录,请对DbContext执行以下操作:
var orphans = myContext.Children.Where(child => String.IsNullOrEmpty(child.ParentId));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.