技术开发 频道

Castle ActiveRecord概述

IT168 技术文档】

    一、ActiveRecord与Castle ActiveRecord

    ActiveRecord是《Patterns of Enterprise Application Architecture》中描述的著名模式。基本上,当实例每一行的时候,所有的静态方法会作用于全部纪录。
    Castle ActiveRecord 是ActiveRecord 模式的一个实现,Castle ActiveRecord依赖Nhibernate来完成实际的映像。与单纯的ActiveRecord 相比,Castle ActiveRecord具有以下特点:

    敏捷开发(它尽可能多地处理了映射和推断,因此,对你的方案而言,当一些东西发生变化的时候,你不必去钻研文档或者处理大量的xml文档)
    预定了像Create, Update, Save, Delete这样的公共方法。
    容易实现像Find, FindAll, FindByName等此类的方法。
    绘画和事务范围(Session and transaction scopes that abstracts the ISession and translates them to a more natural idiom )
    使用Nhibernate,你繁琐的配置工作多于复杂的映射,而使用ActiveRecord却是推进你的生产力的一个保证,你不必再为编写繁冗复杂的映射文件而头疼,ActiveRecord封装了NHibernate的操作,使用特性来代替映射文件,无论何时你需要,ActiveRecord都能给你一个Isession实例,它提供的简洁的O/R映射会让你为实现持久化数据层是那么简单而惊叹!

    Castle的官网是http://www.castleproject.org/,这里的文章都参考于此。

    二、开始

    1、准备工作:

    (1)需要引用的程序集:

Castle.ActiveRecord.dll Castle.Model.dll Nullables.dll NHibernate.dll Castle.DynamicProxy.dll (Curious? Check DynamicProxy) Nullables.NHibernate.dll log4net.dll Iesi.Collections.dll

    (2)一个简单的控制台工程
    (3)数据库

CREATE TABLE Blogs ( blog_id int IDENTITY(1, 1) PRIMARY KEY, blog_name varchar(50), blog_author varchar(50)) CREATE TABLE Posts ( post_id int IDENTITY(1, 1) PRIMARY KEY, post_title varchar(50), post_contents text, post_category varchar(50), post_blogid int FOREIGN KEY REFERENCES Blogs (blog_id), post_created datetime, post_published bit )

    2、编写Blog 类

    首先让我们编写一个继承于ActiveRecordBase的类Blog 。

public class Blog : ActiveRecordBase ...{ }

    接下来你必须使用ActiveRecordAttribute来让Blog 类知道对应数据库的哪个表。注意这件事情,类的名称是Blog ,而数据表的名称是Blogs,如果这两者相同,这个地方可以不特别指定类对应的数据表。

[ActiveRecord("Blogs")] public class Blog : ActiveRecordBase ...{ }

    接下来让我们为类添加属性并指定主键吧:

[ActiveRecord("Blogs")] public class Blog : ActiveRecordBase ...{ private int _id; [PrimaryKey(PrimaryKeyType.Native, "blog_id")] public int Id ...{ get ...{ return _id; } set ...{ _id = value; } } }

    在这个例子中,主键需要对应到数据表中的blog_id字段。与上面相同,如果数据表中主键名称和属性名称相同的话,这个地方也不需要特别指定对应关系,这会使事情更加简单,例如,如果主键的字段名称也是Id,下面这样就可以了:

[PrimaryKey] public int Id ...{ get ...{ return _id; } set ...{ _id = value; } }



    最后让我们来看完成映射关系的类:
using System; using System.Collections.Generic; using System.Text; using Castle.ActiveRecord; namespace ActiveRecord { [ActiveRecord("Blogs")] public class Blog : ActiveRecordBase { private int _id; private String _name; private String _author; [PrimaryKey(PrimaryKeyType.Identity, "blog_id")] public int Id { get { return _id; } set { _id = value; } } [Property("blog_name")] public String Name { get { return _name; } set { _name = value; } } [Property("blog_author")] public String Author { get { return _author; } set { _author = value; } } /**//// <summary> /// 删除所有 /// </summary> public static void DeleteAll() { DeleteAll( typeof(Blog) ); } /**//// <summary> /// 查询所有 /// </summary> /// <returns></returns> public static Blog[] FindAll() { return (Blog[])FindAll(typeof(Blog)); } /**//// <summary> /// 根据Id查询 /// </summary> /// <param name="id"></param> /// <returns></returns> public static Blog Find(int id) { return (Blog)FindByPrimaryKey(typeof(Blog), id); } } }
    我们把类映射到了数据表、字段和主键,代码非常直白。在开始测试之前,我们还必须提供一些配置信息,这些信息包含了数据库联接的一些设置,我们可以使用AppDomain Config文件来保存这些信息,也可以使用硬编码的方式:
<code> <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="activerecord" type="Castle.ActiveRecord.Framework.Config.ActiveRecordSectionHandler, Castle.ActiveRecord"/> </configSections> <activerecord> <config> <add key="hibernate.connection.driver_class" value="NHibernate.Driver.SqlClientDriver" /> <add key="hibernate.dialect" value="NHibernate.Dialect.MsSql2000Dialect" /> <add key="hibernate.connection.provider" value="NHibernate.Connection.DriverConnectionProvider" /> <add key="hibernate.connection.connection_string" value="UID=sa;Password=yourpass;Initial Catalog=test;Data Source=." /> </config> </activerecord> </configuration> </code>
    或者:
InPlaceConfigurationSource source = new InPlaceConfigurationSource(); Hashtable properties = new Hashtable(); properties.Add("hibernate.connection.driver_class", "NHibernate.Driver.SqlClientDriver"); properties.Add("hibernate.dialect", "NHibernate.Dialect.MsSql2000Dialect"); properties.Add("hibernate.connection.provider", "NHibernate.Connection.DriverConnectionProvider"); properties.Add("hibernate.connection.connection_string", "UID=sa;Password=;Initial Catalog=test;Data Source=."); source.Add(typeof(ActiveRecordBase), properties); ActiveRecordStarter.Initialize(source, typeof(Blog));
    在这个例子中,我们可以象下面这样初始化:
IConfigurationSource source = System.Configuration.ConfigurationSettings.GetConfig("activerecord") as IConfigurationSource; ActiveRecordStarter.Initialize(source, typeof(Blog));
    现在你能够象下面这样运行程序了:
//删除所有 Blog.DeleteAll(); //添加 Blog blog = new Blog(); blog.Name = "ttinfo"; blog.Author="ttinfo2"; blog.Save(); // or blog.Create(); //按照id查询 Int id=1; Blog blog= Blog.Find(id); ……
0
相关文章