entity-framework - 有条件的急切加载?

标签 entity-framework entity-framework-4

我想有条件地加载一个实体和它的 child (我只想在 child.IsActive == true 时急切加载 child )。我如何执行以下操作?

var parent = 
    from p in db.tblParents.Include("tblChildren") <-- where tblChildren.IsActive == true
    where p.PrimaryKey == 1
    select p;

注意:我不想返回匿名类型。

谢谢。

最佳答案

这样做的一种方法是:

var parent = from p in db.tblParents where p.PrimaryKey == 1
             select new {
                 Parent = p,
                 Children = p.tblChildren.Where(c => c.IsActive == true)
             }.ToList();

但是,您可能不喜欢返回匿名类型的想法,那么我建议这样编码:
var parent = (from p in db.tblParents where p.PrimaryKey == 1).Single();
var childrens = ctx.Contacts.Where(c => c.ParentID == 1 && c.IsActive == true);
foreach (var child in childrens) {
   parent.tblChildren.Add(child);
}

关于entity-framework - 有条件的急切加载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3718400/

相关文章:

.net - Entity Framework 中联接表的导航属性

c# - IObjectSet 包含 CompiledQuery 的扩展方法错误

c# - 在 Identity 2.0 中扩展 IdentityUserRole

c# - 使用 Entity Framework 模型键入安全 key

c# - 具有十进制值的 asp.net core 2.0 绑定(bind)模型

c# - 在 Entity Framework 上运行原始 SQL 查询的 KeyValuePair

entity-framework - 首先在 Entity Framework 代码中检索关联表中的值

entity-framework - 将项目从 .NET 4.0 升级到 .NET 4.5 后失败 => 找不到类型或命名空间名称 'MaxLength'/'Column'

c# - 获取导致异常的查询

entity-framework-4 - Linq 到实体 : How to copy records from one table to another efficiently?