http://www.rainsts.net/article.asp?id=243
有意无意的,很多文章都没有提及 ActiveRecordMediator 。

ActiveRecordMediator最大的用途是:即便你的实体类不是继承自 ActiveRecordBase (不推荐这么做),它也可以进行同等的创建、查找等操作;另外这个类实现了很多常用的方法,我们直接使用它就没必要为每个实体类写一堆相同的操作方法了(ActiveRecordBase的静态方法干吗声明为 protected internal?)。
[ActiveRecord]
public class User
{
  private int id;

  [PrimaryKey(PrimaryKeyType.Identity)]
  public int Id
  {
    get { return id; }
    set { id = value; }
  }
}

public static void Test()
{
  ActiveRecordMediator.Create(new User());
}

看看下面的类型定义,方法是不是很多?
public class ActiveRecordMediator
{
  public ActiveRecordMediator();
  public static void Create(object instance);
  public static void Delete(object instance);
  public static void DeleteAll(Type type);
  public static void DeleteAll(Type type, string where);
  public static object Execute(Type targetType, NHibernateDelegate call, object instance);
  public static object ExecuteQuery(IActiveRecordQuery q);
  public static Array FindAll(Type targetType);
  public static Array FindAll(Type targetType, params ICriterion[] criterias);
  public static Array FindAll(Type targetType, Order[] orders, params ICriterion[] criterias);
  public static object FindByPrimaryKey(Type targetType, object id);
  public static object FindByPrimaryKey(Type targetType, object id, bool throwOnNotFound);
  public static ISessionFactoryHolder GetSessionFactoryHolder();
  public static void Save(object instance);
  public static Array SlicedFindAll(Type targetType, int firstResult, int maxresults, params ICriterion[] criterias);
  public static Array SlicedFindAll(Type targetType, int firstResult, int maxresults, Order[] orders, params ICriterion[] criterias);
  public static void Update(object instance);
}

当然,Castle 还提供了ActiveRecordMediator<T> 和ActiveRecordBase<T>这两个泛型实现,但不知道为什么没有直接继承自ActiveRecordMediator和ActiveRecordBase,而且还少了一些实用的方法。看来鱼和熊掌不能兼得,当然你可以自己修改代码来的兼而并之。

在ActiveRecordMediator的多个方法中都使用了ICriterion接口,其真正实现是NHibernate.Expression名字空间。我们可以Expression静态类生成许多查询条件。

// 分页查询 (查询100<=id<200 的用户对象集合,返回第1页,每页10条记录)
ActiveRecordMediator.SlicedFindAll(typeof(User), 0, 10, Expression.Between("id", 100, 200));

-----------------

附:本文所有演示代码使用 2006-01-01 发布的 Castle ActiveRecord Beta3 版本。
Castle ActiveRecord 在发布 1.0 版本前可能有很多较大的变化,如演示代码无法编译,建议您参考最新版本的相关文档。
posted on 2008-01-23 07:38  JerryZhao  阅读(699)  评论(0编辑  收藏  举报