3

I have defined a specification as an object of type Expression<Func<User, bool>> like this:

public static Expression<Func<User, bool>> IsSystemUser
{
  get
  {
    return user => user.UserID == -1;
  }
}

This works marvellously with queries written in extension method syntax:

return workspace.GetDataSource<User>().Where(UserSpecifications.IsSystemUser);

But not with Linq query syntax:

return from user in workspace.GetDataSource<User>() where UserSpecifications.IsSystemUser select user;

The compiler gives me cannot implicitly convert type 'Expression<Func<User, bool>>' to 'bool'.

What gives? I thought Linq query syntax was just a cute DSL dressing up the extension method syntax. Can anyone tell me how I might use my lovely specifications with Linq query syntax?

David
  • 15,750
  • 22
  • 90
  • 150

1 Answers1

2

Your query expression is being translated into:

return workspace.GetDataSource<User>()
                .Where(user => UserSpecifications.IsSystemUser);

The lambda expression is introduced implicitly - but you don't want it in this case. So don't use query expression syntax... Given that here the query expression syntax is longer than using the extension methods directly, and introduces more cruft, why would you want it?

Note that you can mix and match like this:

return from user in workspace.GetDataSource<User>()
                             .Where(UserSpecifications.IsSystemUser)
       where user.Name == "Bob"
       orderby user.ID
       select user;
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thanks again. Obviously the example was simplified for SO. I want to use query syntax because expressing joins otherwise is filth itself. Your hybrid solution works nicely though. – David Nov 07 '11 at 13:41
  • I can't accept your answer yet. Have SO not made some kind of special exception for you? – David Nov 07 '11 at 13:43
  • Hmm I cant even compile your example with extensions method syntax. There is no override of Where method that accepts Expression... – Mic Nov 08 '11 at 12:30
  • @Mic: There is for `IQueryable`: http://msdn.microsoft.com/en-us/library/bb535040.aspx – Jon Skeet Nov 08 '11 at 12:31