문제

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?

도움이 되었습니까?

해결책

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;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top