DEV Community

Bhavesh Ramburn
Bhavesh Ramburn

Posted on

4 1

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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs