之前一直在用EF进行开发,现在项目需要使用Nhibernate,其实也不需要自己去配置,框架都配置好了的,但是自己还是想要尝试着去配置下
1.下载必要的dll文件(我直接从原来的项目中拷贝的)
这个就够了
2.Nihibernate的配置
<section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" />
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2"> <session-factory> <property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property> <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property> <property name="connection.driver_class"> NHibernate.Driver.SqlClientDriver </property> <property name="connection.connection_string">Data Source=192.168.2.87;Initial Catalog=db_database1;Persist Security Info=True;User ID=sa;Password=1qaz2wsx~;Connect Timeout=1440;MultipleActiveResultSets=true</property> <!--设置sql语句执行的超时时间 1200s--> <property name="command_timeout">1200</property> <mapping assembly="MvcApplication1.Entity" /> </session-factory> </hibernate-configuration>
3.数据库表->实体类
[Serializable] public class People { public virtual int id { get; set; } public virtual string name { get; set; } public virtual string sex { get; set; } public virtual int age { get; set; } }
4.hbm.xml文件的配置
<?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping assembly="MvcApplication1.Entity" namespace="MvcApplication1.Entity" xmlns="urn:nhibernate-mapping-2.2"> <class name="People" table="people"> <id name="id" type="int" unsaved-value="null" > <column name="id" length="4" sql-type="int" not-null="true" unique="true" index="PK__people__3213E83FB00D67C7"></column> <generator class="native" > </generator> </id> <property name="name" type="String" > <column name="name" length="50" sql-type="varchar" not-null="false" /> </property> <property name="sex" type="String"> <column name="sex" length="50" sql-type="varchar" not-null="false"></column> </property> <property name="age" type="int"> <column name="age" length="4" sql-type="int" not-null="false"></column> </property> </class> </hibernate-mapping>
注意将该文件的属性修改下:
否则报找不到文件
到此配置结束,下面是使用的小例子
//using NHibernate.Cfg; Configuration cfg = new Configuration(); cfg.Configure(); ISessionFactory factory = cfg.BuildSessionFactory(); ISession session = factory.OpenSession(); using (ITransaction tran = session.BeginTransaction()) { List<People> result = session.CreateQuery("from People").List<People>().ToList(); People people = new People { id=1, name = "LiLy", sex = "女", age = 23 }; session.Save(people); }
时间: 2024-11-05 21:33:54