chobo2
chobo2

Reputation: 85775

How to use Linq Contains()?

I am using nHibernate and I need to create a query that does this:

Course Table

CourseId
CourseName

Task Table // course can have many tasks

TaskName
TaskId
CousreId

Now I need to do a contains:

 session
   .Query<Course>()
   .Where(x =>
     x.Tasks.Contains(/* wants a task object. I want to do it on property level. */) &&
     x.CourseId == 1)

How can I change my query to do a Contains on TaskName?

Upvotes: 0

Views: 1805

Answers (5)

Rex Morgan
Rex Morgan

Reputation: 3029

I would try something like this:

var results = session
    .Query<Course>()
    .Where(crs => crs.Tasks.Any(tsk => tsk.TaskName == theName) && crs.CourseId == 1);

Upvotes: 0

Sergey K
Sergey K

Reputation: 4114

If I correctly understood you can use Any method

session.Query<Course>().Where(x => x.Tasks.Any(t => t.Name == "task name")
                                               && x.CourseId == 1);

Upvotes: 1

Kon
Kon

Reputation: 27441

You either have to implement your own IComparer or IEqualityComparer (as I recall, I may be off) and base it on a specific property of the object. Or use Count() or Find() instead. Here's some pseudo code:

session.Query<Course>().Where(x => x.Tasks.Count(t => t.TaskProperty == "something") > 0 && x.CourseId == 1)

Upvotes: 0

Jeff Mercado
Jeff Mercado

Reputation: 134881

Project your Tasks to a TaskName then use contains on that.

var query = session
    .Query<Course>()
    .Where(x => x.Tasks
                 .Select(t => t.TaskName)
                 .Contains(myTaskName)
             && x.CourseId == 1);

Upvotes: 2

Tomas Aschan
Tomas Aschan

Reputation: 60594

Have you tried this?

var results = session.Query<Course>()
      .Where(crs => crs.Tasks.Count(tsk => tsk.TaskName == theName) > 0);

This should count the number of tasks with the correct name (specified in theName in my example), and return all courses that have a count value greater than zero, i.e. all courses that contain a task with the specific name.

Upvotes: 0

Related Questions