Given the hierarchy of objects
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; } }
and DB context
public class MyContext : DbContext { public DbSet<Parent> Parents { get; set; } }
You can enable children and grandchildren using the lambda syntax ( using System.Data.Entity ) as follows:
using (MyContext ctx = new MyContext()) { var hierarchy = from p in ctx.Parents.Include(p => p.Child.GrandChild) select p; }
Lambda syntax prevents query violation if class names are subsequently changed. However, if Parent has ICollection<Child> instead:
public class Parent { public int Id { get; set; } public virtual ICollection<Child> Children { get; set; } }
Lambda syntax no longer works. Instead, you can use string syntax:
var hierarchy = from p in ctx.Parents.Include("Children.GrandChild") select p;
Is string syntax the only option or is there an alternative way to use lambda syntax in this situation?
linq-to-entities entity-framework
Eric J. Feb 10 '13 at 18:57 2013-02-10 18:57
source share