Lambda expression: Where clause for Include list

So, I got something like this:

var myObj = db.SomeObject
              .Include("Tasks")
              .SingleOrDefault(x => x.Id == someObjectId);

if (myObj != null)
{
    myObj.Tasks = myObj.Tasks.OrderBy(x => x.Number).ToList();
}

Here I want to be able to include condition ( where) in my Include, for example: .where task.IsDeleted == false

So I did not find a solution.

I know that I could use wherealong with where I order tasks, but this, however, does not work in the database, but instead uses memory. I want it to run in the database.

Does anyone know how I can do this? If so, is there a way to include the condition order byin the list of tasks on the list?

+5
source share
4 answers

Something like this returns your original object, its child collection is filtered and sorted.

SomeObject a = db.SomeObjects.Where(x => x.Id == someobjectid)
                      .Select(
                          x =>
                          new
                              {
                                  someObject = x,
                                  task = x.Tasks.Where(task => task.IsDeleted == false)
                                                .OrderBy(task => whatever)
                              })
                      .Select(x => x.someObject).Single();

, :

SomeObject a = db.SomeObjects.Where(x => x.Id == someobjectid)
                      .Select(
                          x =>
                          new
                              {
                                  someObject = x,
                                  task = x.Tasks.Where(task => task.IsDeleted == false)
                                                .OrderBy(task => whatever)
                              });
 return a.FirstOrDefault().someObject;
+5

Select.

- , db:

var anonymous = db.SomeObject.Where( x => x.Id == someObjectId )
  .Select( x => new
    {
      SomeObject = x,
      Tasks = x.Tasks
        .Where( o => !o.IsDeleted )
        .OrderBy( o => ... )
    }
  )
  .SingleOrDefault()
;

, :

MyObject myObject = anonymous.SomeObject;
myObject.Tasks = anonymous.Tasks;
+5

The simple answer is: you cannot do this.

Why? Because you are requesting SomeObject.
Each returned SomeObjectcontains all the data referenced, because if it would not represent the actual object in the database.

+2
source

How to get them separately:

var myObj = db.SomeObject
              .SingleOrDefault(x => x.Id == someObjectId);


var tasks = db.SomeObject
              .Where(x => x.Id == someObjectId)
              .SelectMany(x => x.Tasks)
              .Where(x => !x.Deleted);
+1
source

All Articles