Active Record快速入门指南
--Posts表
CREATE TABLE [dbo].[Posts](
[Id] [int] IDENTITY(1,1) PRIMARY KEY,
[Subject] [nvarchar](200) NOT NULL,
[Text] [nvarchar](max) NOT NULL,
[DateAdded] [datetime] NOT NULL,
)
--Comments表
CREATE TABLE[Comments](
[Id] [int] IDENTITY(1,1) PRIMARY KEY,
[Test] [nvarchar](max) NOT NULL,
[Author] [nvarchar](50) NOT NULL,
[DateAdded] [datetime] NOT NULL,
[PostId] [int] NOT NULL
)
GO ALTER TABLE [dbo].[Comments] ADD CONSTRAINT [FK_Comments_Posts2] FOREIGN KEY([PostId])
REFERENCES [dbo].[Posts] ([Id])
GO
如果不用数据库文件,也可以在数据库中创建Blog数据库,然后再创建这两张表。
//Comment实体类
[ActiveRecord("Comments")]//Table Name
public class Comment : ActiveRecordBase<Comment>
{
[PrimaryKey]
public int Id { get; set; } [BelongsTo("PostId")]//FK Column name
public Post Post { get; set; } [Property]
public string Test { get; set; } [Property]
public string Author { get; set; } [Property]
public DateTime DateAdded { get; set; } } //Post实体类
[ActiveRecord("Posts")]
public class Post : ActiveRecordBase<Post>//继承
{
[PrimaryKey]
public int Id { get; set; } [Property]
public string Subject { get; set; } [Property]
public string Text { get; set; } public string ShortText
{
get
{
if (Text.Length > )
{
return Text.Substring(, ) + "...";
}
else
{
return Text;
}
}
} [HasMany]//Collection
public IList<Comment> Comments { get; set; } [Property]
public DateTime DateAdded { get; set; } public static Post FindLastPost()
{
SimpleQuery<Post> q = new SimpleQuery<Post>(@"from Post p order by p.DateAdded desc");
return (Post)q.Execute()[];
}
}
第四步:构建配置信息
<!--ActiveRecord配置-->
<configSections>
<section name="activeRecord" type="Castle.ActiveRecord.Framework.Config.ActiveRecordSectionHandler,Castle.ActiveRecord"></section>
</configSections>
<activeRecord isWeb="true">
<config>
<add key="hibernate.connection.driver_class" value="NHibernate.Driver.SqlClientDriver"/>
<add key="dialect" value="NHibernate.Dialect.MsSql2008Dialect"/>
<add key="hibernate.connection.provider" value="NHibernate.Connection.DriverConnectionProvider"/>
<add key="connection.connection_string" value="Data Source=.;AttachDbFilename=|DataDirectory|\Blog.mdf;user=sa;password=111"/>
<add key="proxyfactory.factory_class" value="NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle"/>
</config>
</activeRecord>
用过NHibernate的朋友一定会对这段配置代码很熟悉,没错,因为ActiveRecord在底层封装了NHibernate,所以这里的配置跟使用NHibernate时的配置一样,同样是指定了数据源驱动,连接字符串等信息。如果使用了配置文件在代码中只要这样去初始化就可以了
//网站放在Application_Start()中
IConfigurationSource source = ConfigurationManager.GetSection("activeRecord") as IConfigurationSource;
Castle.ActiveRecord.ActiveRecordStarter.Initialize(source,typeof(Post),typeof(Comment));
另外一种方式是通过代码指定的方式,但是由于这种方式相当于硬编码了,不大推荐使用这种方式。
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=111;Initial Catalog=Blog;Data Source=."); source.Add( typeof(ActiveRecordBase), properties ); ActiveRecordStarter.Initialize( source, typeof(Post) );
第五步:开始CRUD操作
添加BolgController,添加视图。
//后台代码
public ActionResult Index()
{
Post[] posts = Post.FindAll();
if (posts.Count() > )
{
ViewData["AllPost"] = posts.ToList();
}
return View();
}
<form id="form1" runat="server">
<h2>
Index</h2>
<table>
<tr>
<td>
Id
</td>
<td>
Subject
</td>
<td>
Text
</td>
<td>
DateAdded
</td>
</tr>
<% foreach (var post in (List<Post>)ViewData["AllPost"])
{%>
<tr>
<td>
<%:post.Id.ToString() %>
</td>
<td>
<%:post.Subject %>
</td>
<td>
<%:post.ShortText %>
</td>
<td>
<%:post.DateAdded %>
</td>
</tr>
<%} %>
</table>
</form>
CRUD都是通过实体对象调用方法完成数据库的持久化。




//
// Generated by ActiveRecord Generator
//
//
namespace ActiveRecordDemo
{
using Castle.ActiveRecord; [ActiveRecord("Posts")]
public class Post : ActiveRecordBase
{ private int _id; private string _subject; private string _text; private System.DateTime _dateAdded; private System.Collections.IList _comments; [PrimaryKey(PrimaryKeyType.Native)]
public int Id
{
get
{
return this._id;
}
set
{
this._id = value;
}
} [Property()]
public string Subject
{
get
{
return this._subject;
}
set
{
this._subject = value;
}
} [Property()]
public string Text
{
get
{
return this._text;
}
set
{
this._text = value;
}
} [Property()]
public System.DateTime DateAdded
{
get
{
return this._dateAdded;
}
set
{
this._dateAdded = value;
}
} [HasMany(typeof(Post), Table="Posts", ColumnKey="PostId")]
public System.Collections.IList Comments
{
get
{
return this._comments;
}
set
{
this._comments = value;
}
} public static void DeleteAll()
{
ActiveRecordBase.DeleteAll(typeof(Post));
} public static Post[] FindAll()
{
return ((Post[])(ActiveRecordBase.FindAll(typeof(Post))));
} public static Post Find(int Id)
{
return ((Post)(ActiveRecordBase.FindByPrimaryKey(typeof(Post), Id)));
}
}
}
//
// Generated by ActiveRecord Generator
//
//
namespace ActiveRecordDemo
{
using Castle.ActiveRecord; [ActiveRecord("Comments")]
public class Comment : ActiveRecordBase
{ private int _id; private string _test; private string _author; private System.DateTime _dateAdded; private Post _post; [PrimaryKey(PrimaryKeyType.Native)]
public int Id
{
get
{
return this._id;
}
set
{
this._id = value;
}
} [Property()]
public string Test
{
get
{
return this._test;
}
set
{
this._test = value;
}
} [Property()]
public string Author
{
get
{
return this._author;
}
set
{
this._author = value;
}
} [Property()]
public System.DateTime DateAdded
{
get
{
return this._dateAdded;
}
set
{
this._dateAdded = value;
}
} [BelongsTo("PostId")]
public Post Post
{
get
{
return this._post;
}
set
{
this._post = value;
}
} public static void DeleteAll()
{
ActiveRecordBase.DeleteAll(typeof(Comment));
} public static Comment[] FindAll()
{
return ((Comment[])(ActiveRecordBase.FindAll(typeof(Comment))));
} public static Comment Find(int Id)
{
return ((Comment)(ActiveRecordBase.FindByPrimaryKey(typeof(Comment), Id)));
}
}
}
注意:生成的一对多或者多对一的代码可能需要手动改造一下。
Active Record快速入门指南的更多相关文章
- AngularJS快速入门指南20:快速参考
thead>tr>th, table.reference>tbody>tr>th, table.reference>tfoot>tr>th, table ...
- AngularJS快速入门指南19:示例代码
本文给出的大部分示例都可以直接运行,通过点击运行按钮来查看结果,同时支持在线编辑代码. <div ng-app=""> <p>Name: <input ...
- AngularJS快速入门指南18:Application
是时候创建一个真正的AngularJS单页面应用程序了(SPA). 一个AngularJS应用程序示例 你已经了解了足够多的内容来创建第一个AngularJS应用程序: My Note Save Cl ...
- AngularJS快速入门指南17:Includes
使用AngularJS,你可以在HTML中包含其它的HTML文件. 在HTML中包含其它HTML文件? 当前的HTML文档还不支持该功能.不过W3C建议在后续的HTML版本中增加HTML import ...
- AngularJS快速入门指南16:Bootstrap
thead>tr>th, table.reference>tbody>tr>th, table.reference>tfoot>tr>th, table ...
- AngularJS快速入门指南15:API
thead>tr>th, table.reference>tbody>tr>th, table.reference>tfoot>tr>th, table ...
- AngularJS快速入门指南14:数据验证
thead>tr>th, table.reference>tbody>tr>th, table.reference>tfoot>tr>th, table ...
- AngularJS快速入门指南13:表单
一个AngularJS表单是一组输入型控件的集合. HTML控件 HTML输入型标签标包括: input标签 select标签 button标签 textarea标签 HTML表单 HTML表单将各种 ...
- AngularJS快速入门指南12:模块
AngularJS模块定义了一个application. 模块是一个application中不同部分的容器. application中的所有控制器都应该属于一个模块. 带有一个控制器的模块 下面这个a ...
随机推荐
- Java好文统计( 引用 )
1. java 关于类的路径及编译问题 windows 版本:http://www.ibm.com/developerworks/cn/java/j-classpath-windows/ unix & ...
- sgu 495. Kids and Prizes (简单概率dp 正推求期望)
题目链接 495. Kids and Prizes Time limit per test: 0.25 second(s)Memory limit: 262144 kilobytes input: s ...
- laravel下的团队开发
当你的团队在开发一个大型应用时,该应用的不同部分可能以不同的速度前进.比如,设想下面的场景:一个开发热源被分配 数据层 的backend工作,而另外一个开发人员做front-end和web/contr ...
- Qt之国际化
简介 Qt国际化属于Qt高级中的一部分,本想着放到后面来说,上节刚好介绍了Qt Linguist,趁热打铁就一起了解下. 对于绝大多数的应用程序,在刚启动时,需要加载默认的语言(或最后一次设置的语言) ...
- 几个排序算法的JS实现
最近找工作,复习一下数据结构的知识,看到排序这一块,顺便动手改了一下. 直接插入排序: 插入排序就是把数据分为有序区和无序区,遍历到的数据和有序区域的数据进行比较,找到要插入的位置,插入位置后的数据做 ...
- python练习程序(c100经典例8)
题目: 输出9*9口诀. for i in range(1,10): for j in range(1,i+1): print str(j)+"*"+str(i)+"=& ...
- js二级下拉被flash档住的解决办法
在<object></object>及以内的代码加入到<script>标签对内 <script language="javascript" ...
- Spring AOP简介
AOP简述 AOP的概念早在上个世纪九十年代初就已经出现了,当时的研究人员通过对面向对象思想局限性的分析研究出了一种新的编程思想来帮助开发者减少代码重复提高开发效率,那就是AOP,Aspect-Ori ...
- 判断https
判断https <script> if(window.location.protocol=='https:'){ window.location.href='http://e.abchin ...
- 如何在VMware虚拟机间建立共享磁盘?
在同一台电脑上,有时难免要安装多个虚拟机,存储空间就成了最大的问题,那么如何解决虚拟机的硬盘问题呢,Vmware自带的工具可以很好的解决此问题,下面我们就来看看如何在Vmware虚拟机间建立共享磁盘? ...