morganpdx
morganpdx

Reputation: 1876

Query Entity Framework object and child object with single query

I have two Entity Framework objects with a one-to-many relationship:

widget(parent) and widgetNail(child)

Widget has a text column: Title WidgetNail has a text column: Description

I would like to build a query that will return a list of Widgets that match one of two criteria:

  1. A text string is found in the Widget title, or
  2. The same text string is found in any WidgetNail description.

So far I have this, which doesn't work...

from widget in entities.Widgets
from widgetNail in entities.WidgetNails
where widget.Title.Contains(searchText)
|| widgetNail.Description.Contains(searchText)
select widget).ToList();

Upvotes: 1

Views: 403

Answers (1)

Yakimych
Yakimych

Reputation: 17752

Regarding

2.The same text string is found in any WidgetNail description.

You mean among the current Widget's children?

(from widget in entities.Widgets
where widget.Title.Contains(searchText) || widget.WidgetNails.Any(wn => wn.Description.Contains(searchText))
select widget).ToList();

or fluent syntax:

entities.Widgets.
         Where(w => w.Title.Contains(searchText) ||
                    w.WidgetNails.Any(wn => wn.Description.Contains(searchText))).
         ToList();

Upvotes: 2

Related Questions