Castle.ActiveRecord基本用法

本文仅供自己学习参考

1、ActiveRecordCastle中提供的一个数据访问框架,它在底层封装了NHibernate的操作,使用特性来代替映射文件,它提供的简洁的O/R映射会让你惊叹原来实现持久化数据层是那么简单。下面我们通过一个简单对象的CRUD操作来快速进入Castle ActiveRecord

首先创建数据表:

create table TestNhibernate(
Id int identity(1,1) primary key,
Content text not null,
Remark text)

 2、编写TestNhibernate的实体类,推荐继承ActiveRecordBase的泛型类,提类了一些静态查询查找的方法。

[ActiveRecord("TestNhibernate")]
    public class TestNhibernate:ActiveRecordBase<TestNhibernate>
    {        
        int id;
        [PrimaryKey(PrimaryKeyType.Identity, "Id")]
        public int Id 
        { 
            get{return id;}
            set { id = value; }
        }
        string content;
        [Property("Content")]
        public string Content { get { return content; } set { content = value; } }
        string remark;
        [Property()]
        public string Remark { get { return remark; } set { remark = value; } }        
    }

 TestNhibernate类必须标记ActiveRecord("TestNhibernate")特性,TestNhibernate为表名,PrimaryKey(PrimaryKeyType.Identity, "Id")表示Id为主键,PrimaryKeyType.Identity表示主键自增,为枚举类型,Property("Content")特性,字段名,如数据库字段名为属性名,可以省去Content。

3、编写配置文件

ActiveRecord相关的数据库、数据驱动等信息,最简单的就是使用配置文件,用过NHibernate的朋友一定会对这段配置代码很熟悉,没错,因为ActiveRecord在底层封装了NHibernate,所以这里的配置跟使用NHibernate时的配置一样,同样是指定了数据源驱动,连接字符串等信息。

<configSections>
    <section name="activerecord" type="Castle.ActiveRecord.Framework.Config.ActiveRecordSectionHandler, Castle.ActiveRecord" />
</configSections>
<activerecord>
    <config>
      <add key="connection.driver_class" value="NHibernate.Driver.OdbcDriver"/>
      <add key="dialect" value="NHibernate.Dialect.MsSql2008Dialect"/>
      <add key="connection.provider" value="NHibernate.Connection.DriverConnectionProvider"/>
      <add key="connection.connection_string" value="Driver={SQL Server};server=.;database=test;Integrated Security=true;" />
      <add key="proxyfactory.factory_class" value="NHibernate.ByteCode.Castle.ProxyFactoryFactory,NHibernate.ByteCode.Castle"/>
    </config>
</activerecord>

 4、用代码初始化配置文件

在Gobal.asax文件中的Appliction_start事件中初始化

protected void Application_Start(object sender, EventArgs e)
{   
     IConfigurationSource sources = System.Configuration.ConfigurationSettings.GetConfig("activerecord") as IConfigurationSource;
     ActiveRecordStarter.Initialize(sources, typeof(TestNhibernate));
}

 5、接下来可以操作实体了,添加方法create(),update更新,save()保存

string content = Request["content"];
string remark = Request["remark"];
//TestNhibernate test = TestNhibernate.Find(1);
TestNhibernate test = new TestNhibernate();
test.Content = content;
test.Remark = remark;
test.Save();

 

 

posted @ 2013-04-17 22:53  再美也是伤  阅读(578)  评论(0编辑  收藏  举报