Search code examples
c#linqexpression-treesspecification-pattern

Linq: how to use specifications against associated objects


I'm using specifications in this kind of form:

public static Expression<Func<User, bool>> IsSuperhero
{
  get
  {
    return x => x.CanFly && x.CanShootLasersFromEyes;
  }
}

Now I can use this specification in the form:

var superHeroes = workspace.GetDataSource<User>().Where(UserSpecifications.IsSuperhero);

But I'm not sure how to use the specification against an associated object like this:

var loginsBySuperheroes = workspace.GetDataSource<Login>().Where(x => x.User [ ??? ]);

Is there a way to do this, or do I need to rethink my implementation of specifications?


Solution

  • Obviously:

    var loginsBySuperheroes = workspace.GetDataSource<User>()
      .Where(UserSpecifications.IsSuperhero)
      .SelectMany(x => x.Logins);
    

    This can be fun:

    var secretBillionaires = workspace.GetDataSource<User>()
       .Where(UserSpecifications.IsSuperhero)
       .SelectMany(user => user.Logins)
       .Where(LoginSpecifications.IsSecretIdentity)
       .Select(login => login.DayJob)
       .Where(DayJobSpecifications.IsBillionaire)