code_junkie

Should repositories implement IQueryable<T>?

Nov 11th, 2011
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. public interface IRepository<T> : IQueryable<T>
  2. {
  3. T Save(T entity);
  4. void Delete(T entity);
  5. }
  6.  
  7. public interface IRepository<T>
  8. {
  9. T Save(T entity);
  10. void Delete(T entity);
  11. IQueryable<T> Query();
  12. }
  13.  
  14. from dos
  15. in ServiceLocator.Current.GetInstance<IRepository<DomainObject>>()
  16. where dos.Id == id
  17. select dos
  18.  
  19. from dos
  20. in ServiceLocator.Current.GetInstance<IRepository<DomainObject>>().Query
  21. where dos.Id == id
  22. select dos
  23.  
  24. public interface IRepository<T>
  25. {
  26. IQueryable<T> Find();
  27. void Save(T entity);
  28. void Delete(T entity);
  29. }
  30.  
  31. public class UserRepository : IRepository<User>
  32. {
  33. public IQueryable<User> Find()
  34. {
  35. // Context is some Entity Framework context or
  36. // Linq-to-Sql or NHib or an Xml file, etc...
  37. // I didn't bother adding this, to this example code.
  38. return context.Users().AsQueryable();
  39. }
  40.  
  41. // ... etc
  42. }
  43.  
  44. public void UserServices : IUserServices
  45. {
  46. private readonly IRepository<User> _userRepository;
  47.  
  48. public UserServices(IRepository<User> userRepository)
  49. {
  50. _userRepository = userRepository;
  51. }
  52.  
  53. public User FindById(int userId)
  54. {
  55. return _userRepository.Find()
  56. .WithUserId(userId)
  57. .SingleOrDefault(); // <-- This will be null, if the
  58. // user doesn't exist
  59. // in the repository.
  60. }
  61.  
  62. // Note: some people might not want the FindBySingle method because this
  63. // uber method can do that, also. But i wanted to show u the power
  64. // of having the Repository return an IQuerable.
  65. public User FindSingle(Expression<Func<User, bool>> predicate)
  66. {
  67. return _userRepository
  68. .Find()
  69. .SingleOrDefault(predicate);
  70. }
  71. }
  72.  
  73. public static User WithId(this IQueryable<User> source, int userId)
  74. {
  75. return source.Where(u => u.UserId == userId).SingleOrDefault();
  76. }
Add Comment
Please, Sign In to add comment