使用 Castle ActiveRecord:
由 database (测试于SQL 2005) 直接使用 AR 的 Generator 产生 mapping class (C#/BV.Net) 法:
(前题是你以建好了 database)
- 安装完成后,执行 C:/Program Files/Castle/Bin/net-2.0/Castle.ActiveRecord.Generator.exe
- "Project Explorer" -> "Add DataBase Connection" 做好设定,连接你的 database, 按 ok (p1)
- "ActiveRecord Components" -> 拖拉 "ActiveRecord" 去左方空白 (p2)
- "Project" -> "Generate Code" -> 输入 name space, output dir, code type, ok (p3)
由 mapping class 生成 database table struct 的方法:
- 写好你的 mapping class 一至多个
- ActiveRecordStarter.CreateSchema();
自动生成 database (前题是你以 set 好 ActiveRecordStarter config)
ActiveRecordStarter config code 方式生成配置:
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 " ,
" Data Source=127.0.0.1;Initial Catalog=testDB;Integrated Security=SSPI " );
source.Add( typeof (ActiveRecordBase), properties);
ActiveRecordStarter.Initialize(source, typeof ( DemoClassA ));
ActiveRecordStarter config xml 方式生成配置:
new XmlConfigurationSource( " ..//app.xml " ),
typeof (DemoClassA));
< 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 ="Data Source=127.0.0.1;Initial Catalog=testDB;Integrated Security=SSPI" />
</ config >
</ activerecord >
简单用法( eg: DemoClassA = mapping class, 有一个 pk (id) 和一个 Property (name) )
{
DemoClassA dp = new DemoClassA();
dp.Name = " 工程部 " ;
dp.Save();
}
总结:
- 对于小型的工程,是不错的轻量级快速解决方案
- AR 基层代码量少,无多余设定,清晰
- 提供自动 generator 工具,生产力提升不少 (尢其是配合 power designer)
- 可以不使用 xml 配置,更不易配置出错
- 大部份反回的 error msg 是 NHibernate 的 error msg 因为 Castle 的 ActiceRecord 是封装他的,
而如果你不具备 NHibernate 的知识,可能会不知所云.(我就是没用 NHibernate 故觉得其 error msg 很烦人)
- 对于复杂的统计很难做的好,效率也不太高
- 对于中大型的工程,工程的复杂程度使你用时有绑手绑脚的感觉
- 对于代码安全程度也是偏低,因为使用了大量的 DLL (尢其全是开源的),几乎暴露了所有
logic / business rule, 假如只是自己公司使用而非开发出售的公司会好一点点...
但是如果是大型的工程,因投入的资金和人力,代码安全应是首要考虑,老板可是看得好紧.
(值得一提的是 AR 因为使用了 attributes 使你可以使用混淆器,而 NHibernate
使用 reflection 使你基本上不能对 data class (mapping class) 进行混淆)
castle 2.0 (support .net 2.0 and visual studio 2005) msi file:
http://prdownloads.sourceforge.net/castleproject/Castle.msi?download
src code:
http://prdownloads.sourceforge.net/castleproject/Castle-src.zip?download
http://www.castleproject.org/index.php/ActiveRecord:Getting_Started
http://www.castleproject.org/index.php/ActiveRecord:Mappings#Class
http://www.castleproject.org/index.php/ActiveRecord%2C_.Net_2.0_and_Generics