今天试了一下NHibernate 3.3比之前的版本简单,只需要引入两个dll,这两个dll分别是:Iesi.Collections.dll和NHibernate.dll
通过 http://nhforge.org/ 下载NHibernate的语言件
config文件配置如下
<configSections> <section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler,NHibernate" /> </configSections> <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2"> <session-factory name="NHibernate.Test"> <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property> <property name="connection.connection_string"> Server=(local);initial catalog=数据库名;User ID=sa;Password=密码 </property> <property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property> <property name="show_sql">flase</property> <property name="command_timeout">10</property> <property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property> <mapping assembly="Model"/> </session-factory> </hibernate-configuration>
实体mapping配置文件如下
<?xml version="1.0" encoding="utf-8"?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Model" namespace="Model"> <class name="Model.UserInfo" table="UserInfo" lazy="true"> <id name="Id" column="Id" type="string"> <generator class="assigned" /> </id> <property name="Name" column="Name" type="string" /> <property name="Sex" column="Sex" type="string" /> <property name="Age" column="Age" type="short" /> </class> </hibernate-mapping>
C#代码如下
var config = new Configuration(); config.Configure(); using(var factory = config.BuildSessionFactory()) { using (var session = factory.OpenSession()) { var trans = session.BeginTransaction(); try { var list = session.CreateQuery("from UserInfo where Name=?").SetParameter(0, "小红").List<UserInfo>(); foreach (var item in list) { Console.WriteLine("{0}-{1}", item.Id, item.Name); } } catch (Exception ex) { trans.Rollback(); Console.WriteLine(ex.Message); } Console.Read(); } }
欢迎加入群:254082423
一起学习讨论asp.net mvc
#专柜正品库蕾哈#加绒保暖牛仔裤休闲裤外穿打底裤手机专享包邮8折限时优惠!!(详情请扫描下方二维码)