注意,这个文件的文件属性中的copy to output directory 属性,设置为 copy always。另外,这是告诉程序,每次都要更新这个文件,防止这个文件改了,发布的时候使用的还是老的配置文件。不仅如此,有时候也不能全信VS2010,过程中如果修改了配置文件,最好是clean 后重新编译运行。
【可选】最好也双击这个文件名,把schemas属性设置为:“D:\NetDLL\nhibernate-configuration.xsd” ,注意前面的目录名根据自己的存放位置自行修改(PS,我没有设置,运行也能成功)。各个帖子都这么说,我先不妄下结论。
【5】编写测试project,
随便添加个windows application project,如TestCase,别忘了引用上面提到的那些库文件,然后添加个按钮,按钮事件代码为:(贴上整个类的代码)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TestNH;
using MySql.Data.MySqlClient;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Dialect;
using NHibernate.Driver;
using NHibernate.Mapping.ByCode;
namespace TestCase
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Configuration cfg = new Configuration().Configure("hibernate.cfg.xml");
ISessionFactory factory = cfg.BuildSessionFactory();
ISession session = factory.OpenSession();
ITransaction transaction = session.BeginTransaction();
Product newUser = new Product();
newUser.Id = 3;
newUser.Name = "Joseph Cool";
newUser.Category = "abc123";
// Tell NHibernate that this object should be saved
session.Save(newUser);
// commit all of the changes to the DB and close the ISession
transaction.Commit();
session.Close();
MessageBox.Show("OK!");
}
}
}
这里的调用方式是:
Configuration cfg = new Configuration().Configure("hibernate.cfg.xml");网上的各种奇葩调用方式很多(经测试,问题很多),这里调用方式我没测试,但是肯定可以用于3.3GA版本。
这句话是告诉编译器,我将使用这个配置文件。
网上的写法是:
Configuration cfg = new Configuration();
说是这样也会自动寻找这个文件,虽然我没测试成功。 而且这种写法也十分的不友好。
F5 运行程序把,不会有错了。