我有2个名为Order和Orderrow的类.我使用NHibernate来获取它的连接.
运行NUnit来测试查询时,我得到了一个ADOException:
Logica.NHibernate.Tests.NHibernateTest.SelectAllOrdersFromSupplierNamedKnorrTest:
NHibernate.ADOException : could not execute query
[ SELECT this_.OrderId as OrderId1_1_, this_.CreatedAt as CreatedAt1_1_, this_.ShippedAt as ShippedAt1_1_, this_.ContactId as ContactId1_1_, customer2_.ContactId as ContactId0_0_, customer2_.LastName as LastName0_0_, customer2_.Initials as Initials0_0_, customer2_.Address as Address0_0_, customer2_.City as City0_0_, customer2_.Country as Country0_0_ FROM Order this_ inner join Contact customer2_ on this_.ContactId=customer2_.ContactId ]
[SQL: SELECT this_.OrderId as OrderId1_1_, this_.CreatedAt as CreatedAt1_1_, this_.ShippedAt as ShippedAt1_1_, this_.ContactId as ContactId1_1_, customer2_.ContactId as ContactId0_0_, customer2_.LastName as LastName0_0_, customer2_.Initials as Initials0_0_, customer2_.Address as Address0_0_, customer2_.City as City0_0_, customer2_.Country as Country0_0_ FROM Order this_ inner join Contact customer2_ on this_.ContactId=customer2_.ContactId]
----> System.Data.SqlClient.SqlException : Incorrect syntax near the keyword 'Order'.
Run Code Online (Sandbox Code Playgroud)
在分析由NHibernate创建的SQL时,我注意到Order类正在破坏SQL语句,因为ORDER BY是SQL中的内部关键字.
这是NHibernate中创建的SQL:
SELECT this_.OrderId as OrderId1_1_, this_.CreatedAt as CreatedAt1_1_, this_.ShippedAt as ShippedAt1_1_, this_.ContactId as ContactId1_1_, customer2_.ContactId as ContactId0_0_, customer2_.LastName as LastName0_0_, customer2_.Initials as Initials0_0_, customer2_.Address as Address0_0_, customer2_.City as City0_0_, customer2_.Country as Country0_0_ FROM Order this_ inner join Contact customer2_ on this_.ContactId=customer2_.ContactId
Run Code Online (Sandbox Code Playgroud)
我在SQL Server 2008 Management studio中将其更改为:
SELECT this_.OrderId as OrderId1_1_, this_.CreatedAt as CreatedAt1_1_, this_.ShippedAt as ShippedAt1_1_, this_.ContactId as ContactId1_1_, customer2_.ContactId as ContactId0_0_, customer2_.LastName as LastName0_0_, customer2_.Initials as Initials0_0_, customer2_.Address as Address0_0_, customer2_.City as City0_0_, customer2_.Country as Country0_0_ FROM [Order] this_ inner join Contact customer2_ on this_.ContactId=customer2_.ContactId`
Run Code Online (Sandbox Code Playgroud)
我在表名称Order中添加了括号(就像这样:[Order])并且它是固定的.
但是如何在NHibernate中修复此问题呢?是否有映射XML文件指令才能完成此操作?
(使用VS2008 SP1,SQL Server 2008 SP1,NHibernate 2.0.1 GA)
我想如果你在映射文件中放置引号("["和"]"在SQL Server中,或者你的数据库支持的任何引号),hibernate会在生成查询时引用对象名称.
(也许发布您的映射文件,所以我们可以看看)
请参见本节"5.3.SQL引号的标识符".你基本上需要这个:
<class name="Order" table="`Order`">
Run Code Online (Sandbox Code Playgroud)