ale*_*dev 11 entity-framework entity-framework-4
我想有条件地加载一个实体和它的孩子(我只想在child.IsActive == true时急切地加载孩子).我该如何执行以下操作?
var parent =
from p in db.tblParents.Include("tblChildren") <-- where tblChildren.IsActive == true
where p.PrimaryKey == 1
select p;
Run Code Online (Sandbox Code Playgroud)
注意:我不想返回匿名类型.
谢谢.
这样做的一种方法是:
var parent = from p in db.tblParents where p.PrimaryKey == 1
select new {
Parent = p,
Children = p.tblChildren.Where(c => c.IsActive == true)
}.ToList();
Run Code Online (Sandbox Code Playgroud)
但是,您可能不喜欢返回匿名类型的想法,然后我建议以这种方式编写代码:
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);
}
Run Code Online (Sandbox Code Playgroud)