NHibernate GenericAdoException未处理无法执行查询

时间:2013-12-10 14:09:22

标签: c# nhibernate

我有一个异常“GenericAdoException未处理”无法在我尝试在此行上执行nhibernate示例时执行查询:

var users = session.CreateCriteria<User>().List<User>();

内部异常是:'User'附近的语法不正确

Program.cs上的我的主要方法:

using NHibernate.Cfg;
using NHibernate.Dialect;
using NHibernate.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            var cfg = new Configuration();
            cfg.DataBaseIntegration(x =>
            {
                x.ConnectionString = "Server=.;database=NHibernateTryOutDB;uid=sa;pwd=Hasar2012";
                x.Driver<SqlClientDriver>();
                x.Dialect<MsSql2012Dialect>();
            });
            cfg.AddAssembly(Assembly.GetExecutingAssembly());
            var sessionFactory = cfg.BuildSessionFactory();
            using (var session = sessionFactory.OpenSession())
            using (var tx = session.BeginTransaction())
            {
                var users = session.CreateCriteria<User>().List<User>();
                foreach (User item in users)
                {
                    Console.WriteLine("{0} {1}", item.Name, item.Surname);
                }
                tx.Commit();
            }
            Console.WriteLine("Press <Enter> to exit...");
            Console.ReadLine();
        }
    }
}

我有一个名为Users的表:

USE [NHibernateTryOutDB]
GO

/****** Object:  Table [dbo].[Users]    Script Date: 12/10/2013 16:04:12 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Users](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](50) NULL,
    [Surname] [nvarchar](50) NULL,
 CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

我的班级名称User.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class User
    {
        public virtual int ID { get; set; }
        public virtual string Name { get; set; }
        public virtual string Surname { get; set; }
    }
}

我的.hbm.xm文件是User.hbm.xml:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   assembly="ConsoleApplication2"
                   namespace="ConsoleApplication2">
  <class name="User">
    <id name="ID">
      <generator class="native"/>
    </id>
    <property name="Name"/>
    <property name="Surname"/>
  </class>
</hibernate-mapping>

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:3)

用户是sql中的保留字,您需要在用户周围添加[]或为对象选择其他名称。除此之外,您的表名是Users,而不是映射中的用户。

答案 1 :(得分:0)

首先,检查连接数据库名称,在连接字符串中使用正确的数据库名称。