1.创建一个控制台应用
2.引入dll,这里可以右击引用,点击管理NuGet程序包,然后直接去搜索下载。
我们这里下载MySql.Data和NHibernate
其中mysql用6.10.7的版本
nhibernate用4.12的版本
3. 配置hibernate的config
可以去官网Your first NHibernate based application - NHibernate
找到一个Configure NHibernate
其中我们要更改的是我红色方框圈出来的地方,一个是数据库类型,一个是连接
在项目中添加一个hibernate.cfg.xml,并且改成自己的数据库和连接,注意名字别错!
改动后的文件如下
hibernate.cfg.xml:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="dialect">NHibernate.Dialect.MsSqlCeDialect</property>
<property name="connection.driver_class">NHibernate.Driver.MySqlDataDriver</property>
<property name="connection.connection_string">server=localhost;port=3306;database=gamedb;user=root;password=root</property>
<property name="show_sql">true</property>
</session-factory>
</hibernate-configuration>
4.将hibernate.cfg.xml设置始终复制
5.创建一个Mode文件夹,并且在下面写一个user类
里面写上对应数据库users表里面设置的属性
数据库:
对了说一下。我把我的命名空间改了。
User.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NHiberToMySQL.Model
{
class User
{
public virtual int Id { get; set; }
public virtual string Username { get; set; }
public virtual string Password { get; set; }
public virtual DateTime Registerdate { get; set; }
}
}
6.创建一个Mapping文件夹,并且在其中创建一个名叫User.hbm.xml的配置文件用来做user的映射。
并且注意里面生成操作那一块选择:嵌入的资源。
继续去官网,找到mapping的xml,复制过来改
User.hbm.xml:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="NHiberToMySQL"
namespace="NHiberToMySQL.Model">
<!-- more mapping info here -->
<class name="User" table="users">
<id name="Id" column="id" type="Int32">
<generator class="native"></generator>
</id>
<property name="Username" column="username" type="string"></property>
<property name="Password" column="password" type="string"></property>
<property name="Registerdate" column="registerdate" type="Date"></property>
</class>
</hibernate-mapping>
7.在主程序里面解析配置文件启动
Program.cs:
using NHibernate.Cfg;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NHiberToMySQL
{
class Program
{
static void Main(string[] args)
{
var cfg = new Configuration();
cfg.Configure();//解析配置文件
cfg.AddAssembly("NHiberToMySQL");
}
}
}
最后按ctrl+f5
成功(●'◡'●)