DEV Community

Bhavesh Ramburn
Bhavesh Ramburn

Posted on

Querying parent from child table in EntityFramework

I was looking at getting childrens of a parent table by querying the table only.
To give you a context of the data I had the following models:


// this is the parent class
class Projects {
public Guid Id;
public List<Comments> comments;
... //other fields
}

// this is the child 1-M
class Comments{
public Guid Id;
public Project project;
... //other fields
}

Enter fullscreen mode Exit fullscreen mode

Once I've injected the dbcontext class, I start querying the database the following way with AsQueryable() if you don't put this you won't be able to call up the search by id.

...
var projectId = "<<guid>>"

List<Comment> entity = await _context.Comments.AsQueryable().Where(it => it.Project.Id == projectId ).ToListAsync();
...

Enter fullscreen mode Exit fullscreen mode

doing this, will allow you to query the child's parent's object and return a list

Hope this was helpful

Top comments (0)