Home > Software design >  Entity Framework Core : Select Parent and just one Child
Entity Framework Core : Select Parent and just one Child

Time:01-09

I have a Parent and Child class defined as per usual:

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

public class Child
{
    public int Id { get; set; }
    public string ChildName { get; set; }
}

I have ParentId and ChildId to query with.

I need to select the parent and only 1 child matching the ChildId.

How do I do this in one query?

TIA

CodePudding user response:

Not sure if you can get both in one query, but below should work.

var foundParentEnum =
    from curParent in ListOfParents
    where curParent.Id == parentIdLookingFor
    select curParent;

var foundParent = foundParentEnum.FirstOrDefault();
var foundChild = foundParent.Children.FirstOrDefault();

If you want to find the child in one query.

var foundChildEnum =
    from curParent in ListOfParents
    where curParent.Id == parentIdLookingFor
    select curParent.Children.FirstOrDefault();

Added a JSFiddle to see it working.

CodePudding user response:

The thing you are looking for is called Filtered Include.

In your case the code will be the following:

var parent = dbContext.Parents
                      .Include(p => p.Children
                                     .Where(c => c.Id == childId))
                      .SingleOrDefault(p => p.Id == parentId)
  •  Tags:  
  • Related