持久层使用了LINQ TO SQL。
生成工具采用了T4 模板里面自带的一个linq sql 生成工具。比自带的那个好多了。
持久层用的最多的3个模式
dao,repository, dao+repository
它们之间的区别不说了。我用的是另外一种模式repository+extensions,这种方式比较适合查询语句相对简单的项目。
请看我写的这篇文章【轻量级数据过滤方案】
http://www.cnblogs.com/yuanhuaming/archive/2010/02/05/1664564.html
hibernate , entity framework 这类orm已经提供了很好的条件封装机制,只需提供一个通用的数据访问接口就行了,在社区甚至有人认为使用这些orm根本就不需要dal。
其实linq也可以只使用一个通用接口,只不过我对表达式树不了解,使用方面有困难。
看一下项目中repository的接口
public interface IRepository<T>
{
T Get(object id);
IQueryable<T> FindAll();
bool IsExists(Expression<Func<T, bool>> predicate);
void Add(T entity);
void Add(List<T> entitys);
void Delete(T entity);
void Delete(List<T> entitys);
void Delete(Expression<Func<T, bool>> predicate);
void Save();
}
这里FindAll()方法没有直接返回List集合。数据的加载我基本上都延迟到了Controller再加载的。
延迟到controller层有很多好处:
1.可以减少DTO。 使用匿名类可以直接放入View中,而不需要写一个DTO作中间传输。
2.数据需要时在加载,有效利用资源。
3.IQueryable<T> 的灵活性很高。
这些都会在介绍controller的。
那么复杂查询怎么处理?
我们来看一个简单的例子
这是一个扩展question查询的类
public static class QuestionExtensions
{
public static IQueryable<Question> GetQuestionByUser(this IQueryable<Question> query, string userId)
{
return query.Where(a => a.CreatedBy == userId);
}
}
我们在service层就可以这样使用。
public class QuestionBiz : BaseBiz<Question>
{
private readonly IRepository<Question> _repository;
public QuestionBiz(IRepository<Question> repository)
: base(repository)
{
_repository = repository;
}
public IQueryable<Question> GetQuestionByUser(string userId)
{
return _repository.FindAll().GetQuestionByUser(userId);
}
}
数据处理全部放在了dal,service只负责调用。dal只开放了一个通用接口就可以实现dao+repository模式了。
附上souce了,https://iknowledge.svn.codeplex.com/svn ,程序还未完成,理解就行。