【发布时间】:2013-01-25 22:04:26
【问题描述】:
给定对象层次结构
public class Parent
{
public int Id { get; set; }
public virtual Child Child { get; set; }
}
public class Child
{
public int Id { get; set; }
public virtual GrandChild GrandChild { get; set; }
}
public class GrandChild
{
public int Id { get; set; }
}
和数据库上下文
public class MyContext : DbContext
{
public DbSet<Parent> Parents { get; set; }
}
可以像这样使用 Lambda 语法 (using System.Data.Entity) 包含子孙:
using (MyContext ctx = new MyContext())
{
var hierarchy =
from p in ctx.Parents.Include(p => p.Child.GrandChild) select p;
}
如果类名随后发生更改,Lambda 语法可防止中断查询。但是,如果 Parent 有一个 ICollection<Child> 像这样:
public class Parent
{
public int Id { get; set; }
public virtual ICollection<Child> Children { get; set; }
}
Lambda 语法不再有效。相反,可以使用字符串语法:
var hierarchy = from p in ctx.Parents.Include("Children.GrandChild") select p;
字符串语法是唯一的选择,还是在这种情况下有其他使用 Lambda 语法的替代方法?
【问题讨论】:
-
我不知道你可以在那里使用字符串。这对我帮助很大。
标签: entity-framework linq-to-entities