Rafael Pimenta
Rafael Pimenta

Reputation: 132

hibernate.cfg.xml not found - NHibernate + dot.net core

I'm creating a simple console app to test the nhibernate 5.2.7 using the .net core 3.1.

I just add a App.config to my project:

enter image description here

That is my App.config file content:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" />
  </configSections>
  <connectionStrings>
    <add name="db" connectionString="Server=localhost; Database=NHCookbook;persist security info=True;user id=smo;password=smo;" />
  </connectionStrings>
  <hibernate-configuration xmlns="urn:nhibernate-configuration2.2">
    <session-factory>
      <property name="dialect">NHibernate.Dialect.MsSql2012Dialect</property>
      <property name="connection.connection_string_name">db</property>
      <property name="adonet.batch_size">100</property>
    </session-factory>
  </hibernate-configuration>
</configuration>

That is my main method and the NHibernate configuration:

static void Main(string[] args)
{
    var nhConfig = new Configuration().Configure();
    var sessionFactory = nhConfig.BuildSessionFactory();
    Console.WriteLine("NHibernate Configured!");
    Console.ReadKey();
}

When I run this console application, The follow exception is thrown:

Exception: NHibernate.Cfg.HibernateConfigException: 'An exception occurred during configuration of persistence layer.'

Inner: FileNotFoundException: Could not find file 'D:\@git\stufs\Cookbook\ConfigByAppConfig\bin\Debug\netcoreapp3.1\hibernate.cfg.xml'.

The exception is throw in the follow statement:

var nhConfig = new Configuration().Configure();

csproj:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="NHibernate" Version="5.2.7" />
    <PackageReference Include="System.Data.SqlClient" Version="4.8.1" />
  </ItemGroup>

  <ItemGroup>
    <None Update="App.config">
      <CopyToOutputDirectory>Never</CopyToOutputDirectory>
    </None>
  </ItemGroup>

</Project>

Remark

If I try to configure the Nhibernate by code it works properly:

static void Main(string[] args)
{
    var nhConfig = new Configuration().DataBaseIntegration(db =>
    {
        db.Dialect<MsSql2012Dialect>();
        db.ConnectionStringName = "db";
        db.BatchSize = 100;
    });

    var sessionFactory = nhConfig.BuildSessionFactory();
    Console.WriteLine("NHibernate Configured!");
    Console.ReadKey();
}

Upvotes: 0

Views: 1132

Answers (1)

Morriss
Morriss

Reputation: 31

Try this,

Go to your hibernate.cfg.xml

in the properties, find build action, and set its type to content, and the copy to output directory to Copy Always

enter image description here

Upvotes: 1

Related Questions