EF Core querying data by related IDs

c# entity-framework-core

Question

Suppose I have two classes that have a many-to-one relationship

public class ParentObject{
    public int Id { get; set; }
    public List<ChildObject> Children { get; set; }
    ...
}

public class ChildObject{
    public int Id { get; set; }
    public ParentObject Parent { get; set; }
}

When I add the migration and update the database, the result is two tables:

  • ParentObject
    • Id : int
    • ...
  • ChildObject
    • Id : int
    • ParentObjectId : int
    • ...

Now I want to search for all of the children of a particular parent. In SQL, I can do this without having to join in the parent table simply by querying on the ChildObject.ParentObjectId column.

SELECT * FROM [ChildObject] c WHERE c.ParentObjectId = parentId

But in EF Core, the only way I've found to do this is to use .Include(c => c.Parent) and then .FirstOrDefault(c => c.Parent.Id == parentId). This creates a join to the ParentObject table.

Is there a way to query the ChildObject table without the .Include()?

1
1
1/22/2019 6:38:23 PM

Accepted Answer

Simply use the navigation property to access the parent PK:

var children = db.Children
    .Where(c => c.Parent.Id == parentId)
    .ToList();

If you include some other Parent entity property in Where, OrderBy, Select (or the Parent itself inside Select or Include), of course EF Core will create a join. But if you access only the PK of the related entity, then EF Core is smart enough the use the FK instead and avoid the join.

Please note that the returned Child objects won't have Parent property populated (will be null) except the context is not already tracking a Parent entity instance with that PK.

4
1/23/2019 7:35:15 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow