NHibernate报错:无法识别配置节session-factory求助
嘿,这个问题我之前踩过坑!出现这个错误的核心原因是:.NET 配置系统不知道如何解析session-factory`这个自定义节点——因为它是NHibernate的专属配置节点,你得先告诉.NET该用哪个处理程序来识别它。
下面是具体的解决步骤:
第一步:注册NHibernate配置节处理程序
在你的app.config或web.config里,必须把<configSections>放在<configuration>的最开头,然后添加NHibernate的节定义:<configuration> <!-- 这部分必须是configuration下的第一个节点 --> <configSections> <section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"/> </configSections> <!-- 其他配置节点(比如connectionStrings、appSettings等) --> </configuration>这段代码告诉.NET:碰到名为
hibernate-configuration的节点时,用NHibernate程序集里的ConfigurationSectionHandler来解析它。第二步:把session-factory嵌套在正确的节点里
你不能把session-factory直接放在<configuration>根节点下,必须把它包裹在<hibernate-configuration>内部,正确的结构示例(适配SQL Server 2012):<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2"> <session-factory> <!-- SQL Server 2012专属配置 --> <property name="dialect">NHibernate.Dialect.MsSql2012Dialect</property> <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property> <property name="connection.connection_string">Data Source=你的SQL服务器名;Initial Catalog=你的数据库名;Integrated Security=True;</property> <property name="show_sql">true</property> <!-- 其他NHibernate配置(比如映射文件路径等) --> </session-factory> </hibernate-configuration>第三步:检查NHibernate引用
确保你的项目已经正确引用了NHibernate的程序集(NHibernate.dll),如果是通过NuGet安装的,这个步骤应该已经自动完成,但还是建议确认一下引用是否存在且版本匹配。额外注意:Web应用的config顺序
如果是ASP.NET项目,web.config里的<configSections>必须是<configuration>的第一个子节点,任何其他节点(比如<system.web>)都不能放在它前面,否则.NET会抛出配置节顺序错误的异常。
内容的提问来源于stack exchange,提问作者Lucas Navarro

