利用nhhibernate 去创建数据库表。

1.定义一个实体类

namespace FristSolution.Domain
{
    public class Product
    {
        public virtual Guid Id { get; set; }
        public virtual string Name { get; set; }
        public virtual string Category { get; set; }
        public virtual bool Discontinued { get; set; }
    }
}

2.创建一个mapping文件

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   assembly="FristSolution"
                   namespace="FristSolution.Domain">

  <!-- more mapping info here -->
  <class name="Product">
    <id name="Id">
      <generator class="guid" />
    </id>
    <property name="Name" />
    <property name="Category" />
    <property name="Discontinued" />
  </class>
</hibernate-mapping>


3.创建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.SqlServerCeDriver</property>
    <property name="connection.connection_string">Data Source=FirstSample.sdf</property>

    <property name="show_sql">true</property>
  </session-factory>
</hibernate-configuration>

4.新起动一个项目开始测试

创建测试类。同时把hibernate.cfg.xml复制过来。

[TestFixture]
    public class GenerateSchema_Fixture
    {
        [Test]
        public void Can_generate_schema()
        {
            var cfg = new Configuration();
            cfg.Configure();
            cfg.AddAssembly(typeof(Product).Assembly);

            new SchemaExport(cfg).Execute(true, true, false);
        }
    }

5.测试项目中添加对以下文件的引用

其中sqlserver.ce要在属性中设置拷贝到本地。

1566546216997

配置测试项目

配置的时候把sqlce开头的dll拷贝到项目的输出目录中。

SharedLibs的文件是nhibernate中下载的。

copy $(ProjectDir)..\..\SharedLibs\sqlce*.dll $(ProjectDir)$(OutDir)

1566546765591

6.添加本地数据库,用于测试

1566546315075

7.用testdriven.net工具测试 或者用resharper测试

1566546501155

如果用resharper自带的测试,直接点左边的蓝红点,就可以测试 ,或者用testdriven.net测试 。

直接右击,选择run tests就可以了。

testdriven.net 下载链接:https://pan.baidu.com/s/1myooXty-ZzNcV5BUZbgMuw
提取码:aqtq

注意:

nhibernate使用3.0版本, Iesi.Collections.dll 也使用3.0版本。

版本不同,调用方式会有区别


本文由 hcb 创作,采用 知识共享署名 3.0,可自由转载、引用,但需署名作者且注明文章出处。

还不快抢沙发

添加新评论