3

Given something like:

public class Parent
{
    public int Id { get; set; }
    public List<Child> Children { get; set; }
}

// There is no reference to the parent in the object model
public class Child
{
    public int Id { get; set; }
    public string MyProperty { get; set; }
}

is it possible to load only a child matching a particular condition, for a given Parent ID, without also loading the parent entity?

I have seen solutions that use projection to load the parent and zero or more children matching a condition.

Community
  • 1
  • 1
Eric J.
  • 147,927
  • 63
  • 340
  • 553
  • How does your data model work if a child has no idea what it's parent is? – Alastair Pitts Feb 26 '13 at 05:04
  • why not `db.Childs.Where(c => c.MyProperty == "something")`? – cuongle Feb 26 '13 at 05:06
  • @CuongLe: That does not filter on the parent ID. – Eric J. Feb 26 '13 at 05:24
  • @AlastairPitts: The data model knows, but the object model does not. EF creates a column to represent the relationship in the child table, but does not expose it to the object model unless the parent object is expressly included as a property of the child object. – Eric J. Feb 26 '13 at 05:25
  • @EricJ. Ah. That makes sense, also makes it hard. Any specific reason the parent is not included as a property of the child? – Alastair Pitts Feb 26 '13 at 05:34

1 Answers1

5

If I understand you correctly, this should do it; it puts the conditions you want on both the parent and child, but selects only the child.

from parent in db.Parents
from child in parent.Children
where parent.Id = 4711 &&
      child.MyProperty == "olle"
select child;
Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294