五、使用這些類
現在你已經瞭解了ActiveRecord的大部分了。我們下面就要使用這些類了。你會發現沒有比這更順手的了。
建立第一個使用者
我的應用程式都一般都有登入視窗。你必須輸入正確的登入名稱和密碼通過驗證才能正常使用。即使建立了表User那怎麼添加用記呢?
下面這段代碼就會創始一個user,把它添加到main函數當中。
User user = new User("admin", "123");
user.Create();
當你多次運行程式的時候會發生什麼呢?一個比較好的解決方案是只有當數庫中找不到使用者的時候才新添一個使用者。我們會檢查資料庫中是否存在使用者並且為0的時候可以插入資料。
if (User.GetUsersCount() == 0)
{
User user = new User("admin", "123");
user.Create();
}
顯然我們需要添加一個方法GetUsersCount到User類當中:
[ActiveRecord("[User]")]
public class User : ActiveRecordBase<User>
{
...
public static int GetUsersCount()
{
return Count();
}
}
登入框
這相視窗要求使用者輸入登入資訊:
這段代碼非常簡單,利用搜尋方法找到使用者,到目前為止並沒有擴充方法:
private void logInButton_Click(object sender, System.EventArgs e)
{
User user = User.FindByUserName(loginText.Text);
if (user == null)
{
MessageBox.Show(this, "User not found", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (user.Password != passwordText.Text)
{
MessageBox.Show(this, "Wrong password", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
DialogResult = DialogResult.OK;
Hide();
}
為了完成這個功能,裡面的一個FindByUserName方法,它其實是很簡單的:
using NHibernate.Criterion;
[ActiveRecord("[User]")]
public class User : ActiveRecordBase<User>
{
...
public static User FindByUserName(string userName)
{
// Note that we use the property name, _not_ the column name
return FindOne(Expression.Eq("Username", userName));
}
}
(關鍵是看懂那個 FindOne(Expression.Eq("Username", userName)))
部落格的管理
在這個視窗中它提供了新增,修改和刪除一個Blog.它也提供了所選部落格的管理欄目公告視窗的入口。
當點擊新增時... 或編輯某一個部落格時,另一個視窗就顯示出來。
以下方法從BlogList 中選出所有的blog類:(blog列表顯示的)
private void PopulateBlogList()
{
blogsList.Items.Clear();
foreach(Blog blog in Blog.FindAll())
{
ListViewItem item = blogsList.Items.Add(blog.Id.ToString());
item.Tag = blog;
item.SubItems.Add(blog.Name);
item.SubItems.Add(blog.Author);
}
}
為了在資料庫新增一下部落格記錄我們需要如下做
Blog blog = new Blog();
blog.Name = "My blog";
blog.Author = "hammett";
blog.Create()
假設你不知道blog執行個體,但是你知道它的Id,我們仍然可以修改部落格:
Blog blog = Blog.Find(100); // Id that we know exists
blog.Name = "Different name";
blog.Author = "Different author";
blog.Update();
要想刪除一個執行個體,只要調用Delete方法就行了.
對公告欄目的管理
對於這個公告欄目我們仍沒有忘記它是依賴於部落格執行個體的,當我們建立的時候就要注意了:
urrentPost.Blog = parentBlog;
currentPost.Title = titleText.Text;
currentPost.Contents = contentsText.Text;
currentPost.Category = categoryText.Text;
currentPost.Created = createdDtTime.Value;
currentPost.Published = publishedCheck.Checked;
currentPost.Save();