简体   繁体   中英

EF Core querying data by related IDs

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() ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM