Castle ActiveRecord学习实践(1)入门

首先什么是Active Record

Active Record 是一种领域模型的设计模式,特点是关系数据库中的每张表都对应一个模型类。业务对象表示数据表中的一行记录,并且包含数据,行为以及持久化该对象的工具。每个业务对象均负责自己的持久化和相关的业务逻辑。

Active Record 适用于:

业务逻辑比较简单;数据模型和业务模型之间具有一对一映射关系的简单应用程序。因为业务对象与数据库中的表具有一对一的映射关系,均具有相同的创建、读取、更新和删除(CRUD)方法,可以使用代码生成工具自动生成业务模型。

Castle ActiveRecord

Castle ActiveRecord是最流行的开放源代码的Active Record框架之一,它本身基于NHibernate,只是封装了NHibernate的大部分繁杂的细节,对需要持久化的类,只需要继承自NHibernate,再对类的属性赋予正确的 Attribute。

下载地址:http://www.castleproject.org/ 看清楚是Castle ActiveRecord

一个简单的例子

以一个博客作为demo 2张数据表 post comment

数据表放到附件里面

建立 Comment Post 类

 1     [ActiveRecord("Comments")]
 2     public class Comment:ActiveRecordBase<Comment>
 3     {
 4         [PrimaryKey("CommentId")]
 5         public int Id { get; set; }
 6 
 7         [Property]
 8         public string Text { get; set; }
 9 
10         [Property]
11         public string Author { get; set; }
12 
13         [Property]
14         public DateTime DateAdded { get; set; }
15 
16         [BelongsTo("PostId")]
17         public Post Post { get; set; }
18 
19     }
 1     [ActiveRecord("Posts")]
 2     public class Post:ActiveRecordBase<Post>
 3     {
 4         [PrimaryKey("PostId")]
 5         public int Id { get; set; }
 6 
 7         [Property]
 8         public string Subject { get; set; }
 9 
10         [Property]
11         public string Text { get; set; }
12 
13         [Property]
14         public DateTime DateAdded { get; set; }
15 
16         [HasMany]
17         public IList<Comment> Comments { get; set; }
18 
19           
20     }

2个类都继承自ActiveRecordBase,类的属性用特性修饰,Castle ActiveRecord保证了类的属性和数据库表的列相匹配。

配置文件的设置

 1 <configSections>
 2     <section name="activeRecord" type="Castle.ActiveRecord.Framework.Config.ActiveRecordSectionHandler,Castle.ActiveRecord"/>
 3   </configSections>
 4   <activeRecord isWeb="true">
 5     <config>
 6       <add key="hibernate.connection.driver_class" value="NHibernate.Driver.SqlClientDriver"/>
 7       <add key="dialect" value="NHibernate.Dialect.MsSql2005Dialect"/>
 8       <add key="hibernate.connection.provider" value="NHibernate.Connection.DriverConnectionProvider"/>
 9       <add key="connection.connection_string" value="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Blog.mdf;Integrated Security=True;User Instance=True"/>
10       <add key="proxyfactory.factory_class" value="NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle"/>
11     </config>
12   </activeRecord>

Global文件

1         protected void Application_Start(object sender, EventArgs e)
2         {
3             IConfigurationSource source = ConfigurationManager.GetSection("activeRecord") as IConfigurationSource;
4             Castle.ActiveRecord.ActiveRecordStarter.Initialize(source, typeof(Post), typeof(Comment));
5         }

附件 Castle.zip

posted @ 2012-10-08 23:31  Ian.w  阅读(347)  评论(0编辑  收藏  举报