五、使用这些类
现在你已经了解了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();