如何配置NHibernate连接SQL Server?

问题描述 投票:0回答:2

我的 NHibernate 配置与 SQL Server 数据库的连接遇到了一个小问题。我的应用程序结构仅用于简单测试。这是我的

hibernate.xml.cfg
:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration>
    <session-factory xmlns="urn:nhibernate-configuration-2.2">
        <property name="hibernate.connection.driver_class">net.sourceforge.jtds.jdbc.Driver</property>
        <property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
        <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
        <property name="connection.url">jdbc:jtds:sqlserver://OUSSEMA;DatabaseName=DB_GestionCompte</property>
        <property name="connection.username">sa</property>
        <property name="connection.password">123</property>
        <property name="show_sql">true</property>
    </session-factory>
</hibernate-configuration>

我在运行项目时遇到此错误:

System.TypeInitializationException: 'The type initializer for 'HibernateUtil' threw an exception.'
HibernateConfigException: An exception occurred parsing configuration :The 'name' attribute is invalid - The value 'connection.url' is invalid according to its datatype 'Union' - The value 'connection.url' is not valid according to any of the memberTypes of the union.

上述错误是在以下代码行中引发的:

DataService.cs

ISessionFactory factory = HibernateUtil.GetSessionFactory();

我尝试了不同的 NHibernate 配置方法,但没有一个有效。同时我确信 SQL 身份验证有效且线路正确。

sql-server hibernate configuration nhibernate connection-string
2个回答
0
投票

以下属性名称有效;您需要根据您的配置更改值:

<?xml version="1.0"?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
    <session-factory>
        <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
        <property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
        <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
        <property name="connection.connection_string">Data Source=SQLServer;Initial Catalog=DBName;User ID=SQLUser;Password=SQLPassword</property>
        <property name="default_schema">[XYZ].[dbo]</property>
        <property name="connection.isolation">ReadCommitted</property>
        <property name="show_sql">false</property>
        <mapping assembly="MyMappingsAssembly"/>
    </session-factory>
</hibernate-configuration>

但是,您可以选择通过代码来完成所有这些操作,而不是使用 XML 配置。请参阅this答案,其中解释了如何做到这一点。 other 答案解释了如何将 SQL 查询记录到文件中。


0
投票

查看文档,您的配置似乎使用了无法识别的属性名称。

例如,

connection.url
,应该是
connection.connection_string
。我在文档中看不到
connection.username
connection.password
的等效项。这些通常包含在连接字符串中。

© www.soinside.com 2019 - 2024. All rights reserved.