install-package nhibernate
install-package nunit
Customer.cs
public class Customer { public virtual Guid ID { get; set; } public virtual string Name { get; set; } public virtual string City { get; set; } }
Customer.hbm.xml,需要设置为嵌入式资源,并与相应CS文件同DLL
<?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="NHi.Domain" namespace="NHi.Domain.Entities"> <class name="Customer" table="Customer"> <id name="ID" column="ID" type="Guid" > <generator class="assigned" /> </id> <property name="Name" type="string"> <column name="Name" sql-type="varchar(20)" not-null="false" /> </property> <property name="City" type="string"> <column name="City" sql-type="nvarchar(500)" not-null="false" /> </property> </class> </hibernate-mapping>
hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?> <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2" > <session-factory name="NHi.Test"> <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property> <property name="connection.connection_string">server=local;database=NHiDemo;uid=sa;pwd=123456;</property> <property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property> <property name="hbm2ddl.auto">update</property> <!--貌似只能添加列,对删除列,修改类型/长度不起作用,待续。。。--> <mapping assembly="NHi.Domain"/> </session-factory> </hibernate-configuration>
BaseTest.cs
public class BaseTest { protected ISessionFactory sessionFactory; [SetUp] public void Init() { var cfg = new NHibernate.Cfg.Configuration().Configure("Config/hibernate.cfg.xml"); sessionFactory = cfg.BuildSessionFactory(); }
[TearDown]
public void Teardown()
{
}
}
CustomerTest.cs
[TestFixture] public class CustomerTest:BaseTest { [Test] public void Add() { object o = null; using (ISession session = sessionFactory.OpenSession()) { var customer = new NHi.Domain.Entities.Customer() { ID = Guid.NewGuid(), Name = "your name", City = "my city" }; o=session.Save(customer); session.Flush(); } Assert.NotNull(o); } }
NuGet 包:
扩展和更新: