Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public interface IRepository<T> : IQueryable<T>
- {
- T Save(T entity);
- void Delete(T entity);
- }
- public interface IRepository<T>
- {
- T Save(T entity);
- void Delete(T entity);
- IQueryable<T> Query();
- }
- from dos
- in ServiceLocator.Current.GetInstance<IRepository<DomainObject>>()
- where dos.Id == id
- select dos
- from dos
- in ServiceLocator.Current.GetInstance<IRepository<DomainObject>>().Query
- where dos.Id == id
- select dos
- public interface IRepository<T>
- {
- IQueryable<T> Find();
- void Save(T entity);
- void Delete(T entity);
- }
- public class UserRepository : IRepository<User>
- {
- public IQueryable<User> Find()
- {
- // Context is some Entity Framework context or
- // Linq-to-Sql or NHib or an Xml file, etc...
- // I didn't bother adding this, to this example code.
- return context.Users().AsQueryable();
- }
- // ... etc
- }
- public void UserServices : IUserServices
- {
- private readonly IRepository<User> _userRepository;
- public UserServices(IRepository<User> userRepository)
- {
- _userRepository = userRepository;
- }
- public User FindById(int userId)
- {
- return _userRepository.Find()
- .WithUserId(userId)
- .SingleOrDefault(); // <-- This will be null, if the
- // user doesn't exist
- // in the repository.
- }
- // Note: some people might not want the FindBySingle method because this
- // uber method can do that, also. But i wanted to show u the power
- // of having the Repository return an IQuerable.
- public User FindSingle(Expression<Func<User, bool>> predicate)
- {
- return _userRepository
- .Find()
- .SingleOrDefault(predicate);
- }
- }
- public static User WithId(this IQueryable<User> source, int userId)
- {
- return source.Where(u => u.UserId == userId).SingleOrDefault();
- }
Add Comment
Please, Sign In to add comment