Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return Only Child Entity Linq Entity Framework

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.

like image 394
Eric J. Avatar asked Dec 03 '25 18:12

Eric J.


1 Answers

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;
like image 139
Joachim Isaksson Avatar answered Dec 06 '25 22:12

Joachim Isaksson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!