Nhibernate

开始研究Nhibernate,解决很多问题后算是可以查询了,关键点记录如下:

 (比较幸运,这里的问题遇到大半)

1.web.config中添加配置 (注意NHibernate版本问题)

<section name="hibernate-configuration"
    type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" />

<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
    <session-factory>
      <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider </property>
      <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver </property>
      <property name="connection.connection_string">server=127.0.0.1;user id=sa;password=sa;database=SShop</property>
      <property name="show_sql">true </property>
      <property name="dialect">NHibernate.Dialect.MsSql2005Dialect </property>
      <property name="use_outer_join">true </property>
      <property name="query.substitutions">true 1, false 0, yes 'Y', no 'N' </property>
      <!-- mapping files 暂时不知这个为何不起作用,需要写代码映射-->
      <mapping assembly="OOne.Mvc.Models"/>

    </session-factory>
  </hibernate-configuration>

 

 2.创建数据表/影射文件/实体类(virtual )

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
  <class name="OgilvyOne.Mvc.Models.NhTest, OgilvyOne.Mvc.Models" table="NhTest">
    <id name="F1" column="f1" type="Int32">
      <generator class="native" />
    </id>
    <property name="F2" column= "f2" type="Int32" />
  </class>
</hibernate-mapping>

映射文件--右键--属性--生成操作(内容-->潜入资源)   编译后就在dll中了

public class NhTest
    {
        public NhTest() { }
        private int f1;
        private int f2;
        public virtual int F1
        {
            get { return f1; }
            set { f1 = value; }
        }
        public virtual int F2
        {
            get { return f2; }
            set { f2 = value; }
        }
    }

 3.创建会话工厂类

  NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();
                            //cfg.AddAssembly( Assembly.GetExecutingAssembly() );
                            //cfg.AddXmlFile("OOne.Mvc.View/bin/NhTest.hbm.xml");  //加载的默认路径不知道是什么,而且会改变--至少我遇到了,配置文件中的配置不起作用,改用下面代码加载程序集
                            cfg.AddAssembly("OOne.Mvc.Models");
                            _factory = cfg.BuildSessionFactory();

 4.调用

Sessions.Factory.OpenSession().CreateQuery(" from NhTest ").List().Count

 

posted on 2009-07-02 19:08  走向前  阅读(751)  评论(0编辑  收藏  举报