2011-07-02 40 views
0

我嘗試使用此教程:Hello NHibernate不能EXCUTE查詢NHibernate的

這是我的配置NHibernate的文件:

<?xml version="1.0"?> 
<configuration> 
    <configSections> 
    <section name="hibernate-configuration" requirePermission="false" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"/> 
    </configSections> 
    <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2"> 
    <reflection-optimizer use="false"/> 
    <session-factory> 
     <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property> 
     <property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property> 
     <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property> 
     <property name="connection.connection_string">Data Source=.\SQLEXPRESS; Initial Catalog=dbTest; Trusted_Connection=true;</property> 
     <property name="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property> 
     <property name="show_sql">true</property> 
     <mapping resource="TestNHibernate.user.hbm.xml" assembly="TestNHibernate"/> 
    </session-factory> 
    </hibernate-configuration></configuration> 

這是我的映射文件:

​​

類用戶:

class user 
    { 

     public virtual int Id { get;set; } 
     public virtual string Name { get; set; } 
    } 

這裏是查詢代碼:

Configuration config = new Configuration(); 
       config.AddAssembly(typeof(user).Assembly); 
       ISessionFactory sessionFactory = config.BuildSessionFactory(); 

       using (var session = sessionFactory.OpenSession()) 
       {     
        IQuery query = session.CreateQuery("from user as u"); 
        IList<user> lst = query.List<user>(); 
        foreach (var user in lst) 
        { 
         Console.WriteLine(user.Name); 
        } 
       } 

它總是提示錯誤:

could not execute query [ select user0_.Id as Id0_, user0_.Name as Name0_ from user user0_ ] [SQL: select user0_.Id as Id0_, user0_.Name as Name0_ from user user0_]

我試圖插入,更新,但它也表明無法插入,更新。我的問題在哪裏?

是否有我的映射文件? 請給我建議!謝謝!

回答

1

兩件事情:

(1)在你的映射文件,你應該圍繞用戶表中括號,例如[用戶]。用戶是SQL Server中的保留關鍵字(以及大多數其他SQL系統)。 (2)當您在NHibernate中遇到異常時,進入調試模式並查看內部異常。這些通常提供了有關問題的線索。

+0

非常感謝。這對我很有用 – R4j

0

確保映射中的表名和列名與數據庫模式中定義的名稱完全一致。根據您的SQL Server配置,區分大小寫也可能很重要。

1

如果使用此代碼,NHibernate將生成數據庫模式和數據庫腳本,以防止區分大小寫或其他錯誤。

var conf = new NHibernate.Cfg.Configuration(); 
     conf.Configure(); 


     var export = new SchemaExport(conf); 
     export.SetOutputFile(@"DatabaseScript.sql"); 
     export.Drop(true, true); 
     export.Create(true, true); 

我認爲「用戶」可以是保留字!嘗試:

IQuery query = session.CreateQuery("from [user] as u");