二,建立類
現在我們來依據表來建立類,這裡你將看到有多方便。首先我們來從一個最簡單的開始User類:
建立使用者類
1、建立一個名字是User的類加上命名空間
namespace BlogSample
{
using System;
using Castle.ActiveRecord;
public class User
{
}
}
2、現在來用ActiivRecordBase 中的ActiveRecordAttribute來擴充這個類:
namespace BlogSample
{
using System;
using Castle.ActiveRecord;
[ActiveRecord]
public class User : ActiveRecordBase<User>
{
}
}
3、根據表中的列來增加相應的類的屬性
namespace BlogSample
{
using System;
using Castle.ActiveRecord;
[ActiveRecord]
public class User : ActiveRecordBase<User>
{
private int id;
private string username;
private string password;
private int Id
{
get { return id; }
set { id = value; }
}
public string Username
{
get { return username; }
set { username = value; }
}
public string Password
{
get { return password; }
set { password = value; }
}
}
}
4、 最後在類中添加標識標明在ActiveRecord中對應的是什麼屬性(即簡單的屬性對應到列,主鍵或關係)。在本例中Id標識為主鍵,其他的標識為普通屬性:
namespace BlogSample
{
using System;
using Castle.ActiveRecord;
[ActiveRecord]
public class User : ActiveRecordBase<User>
{
private int id;
private string username;
private string password;
public User()
{
}
public User(string username, string password)
{
this.username = username;
this.password = password;
}
[PrimaryKey]
private int Id
{
get { return id; }
set { id = value; }
}
[Property]
public string Username
{
get { return username; }
set { username = value; }
}
[Property]
public string Password
{
get { return password; }
set { password = value; }
}
}
}
就是這樣簡單,現在我們來分別建立Blog和Post類,過程和上面的一樣,建議你自己試著寫一下。
建立部落格類
這個部落格是很簡單的,但是應該注意它是不完全的。我們仍然需要建立它和Post表的關聯,但是這隻需要一分鐘:
namespace BlogSample
{
using System;
using System.Collections;
using Castle.ActiveRecord;
[ActiveRecord]
public class Blog : ActiveRecordBase<Blog>
{
private int id;
private String name;
private String author;
public Blog()
{
}
[PrimaryKey]
private int Id
{
get { return id; }
set { id = value; }
}
[Property]
public String Name
{
get { return name; }
set { name = value; }
}
[Property]
public String Author
{
get { return author; }
set { author = value; }
}
}
}
創始Post類
這個Post類也非常簡單,但是它也不完整,我們需要把它和Blog類關聯起來。
這裡我也要注意它和其它的類一點不同,這個Contents 屬性用了[Property(ColumnType="StringClob")]
這樣做是因為我要把該列和類型是text的資料行繫結起來。
namespace BlogSample
{
using System;
using Castle.ActiveRecord;
[ActiveRecord]
public class Post : ActiveRecordBase<Post>
{
private int id;
private String title;
private String contents;
private String category;
private DateTime created;
private bool published;
public Post()
{
created = DateTime.Now;
}
[PrimaryKey]
private int Id
{
get { return id; }
set { id = value; }
}
[Property]
public String Title
{
get { return title; }
set { title = value; }
}
[Property(ColumnType="StringClob")]
public String Contents
{
get { return contents; }
set { contents = value; }
}
[Property]
public String Category
{
get { return category; }
set { category = value; }
}
[Property]
public DateTime Created
{
get { return created; }
set { created = value; }
}
}
}
也許你會說這很容易,即使這是您第一次使用的ActiveRecord。同樣的添加關係也不會太困難。