五、使用這些類
現在你已經瞭解了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();