就个人而言,我使用Repository Pattern 将存储库中的所有项目作为IQueryable 返回。通过这样做,我的存储库层现在变得非常轻、小......服务层(它消耗存储库层)现在可以对所有类型的查询操作开放。
基本上,我所有的逻辑现在都位于服务层(它不知道它将使用什么类型的存储库......并且不想知道
例如。或多或少的伪代码,因为我记得我们在代码中做了什么并为这个答案简化了它......
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);
}
}
奖励积分:FindById 方法中的 WTF 是 WithUserId(userId)?那是Pipe and Filter。使用它们 :) 爱它们 :) 拥抱它们 :) 它们使您的代码非常易读 :) 现在,如果您想知道它的作用.. 这是扩展方法。
public static User WithId(this IQueryable<User> source, int userId)
{
return source.Where(u => u.UserId == userId).SingleOrDefault();
}
尽管这个问题是 .. 嗯... 快两年了 :)