2

When I use FluentNHibernate, it is not able to read connection string from web.config. I am using ASP.NET Core Web Application (.NET Framework), Fluent NHibernate 2.0.3 and NHibernate 4.0.0.4000.

The commented way works fine to access the database, while the not commented one does not work.

        return Fluently.Configure()
            //.Database(MySQLConfiguration.Standard.ConnectionString("Server=localhost;Port=3307; Uid=root; Pwd=usbw;Database=hellonhibernate"))
            .Database(MySQLConfiguration.Standard.ConnectionString(c => c.FromConnectionStringWithKey("TRP123456")))
            .Mappings(m => m.FluentMappings.AddFromAssemblyOf<PersonMap>())
            .Mappings(m => m.FluentMappings.AddFromAssemblyOf<SessionMap>())
            .ExposeConfiguration(CreateSchema)
            .BuildSessionFactory();

The web.config is

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.webServer>
    <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified"/>
    </handlers>
    <aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false"/>
    </system.webServer>
    <connectionStrings>
        <add name="TRP123456" connectionString="server=localhost;port=3307;uid=root;password=admin;database=hellonhibernate;" providerName="MySql.Data.MySqlClient"/>
    </connectionStrings>
</configuration>

This is the error I got. Please help to see what is wrong. Thank you.

enter image description here

The structure of the project is as follow

enter image description here

Ben
  • 957
  • 1
  • 11
  • 37
  • Try to change: `Database(MySQLConfiguration.Standard.ConnectionString(c => c.FromConnectionStringWithKey("TRP123456")))` to `Database(MySQLConfiguration.Standard .ConnectionString(ConfigurationManager.ConnectionStrings["TRP123456"].ConnectionString)))` – Roman Jan 22 '17 at 08:53
  • Hi Roma, thank you for your help. However, it seems does not work. I changed the code to the following but still get Null error. Database(MySQLConfiguration.Standard.ConnectionString(ConfigurationManager.ConnectionStrings["TR‌​P123456"].ConnectionString)) – Ben Jan 22 '17 at 09:24
  • are you sure that you put connection string in right `config` file. Do you have only one application? – Roman Jan 22 '17 at 09:26
  • Hi Roma, I am sure I put the connectionString in web.config, where people usually put it. I attached an image to show my project structure, as well as the web.config structure. Thank you. – Ben Jan 22 '17 at 10:46

1 Answers1

1

First check this question I think it might solve your problem Access WebConfig in DotNet Core

Another solution is to use appsettings.json file instead.

You can do that by adding a json file to your project. Same folder as project.json file.

In your startup.cs you just map your file to your app configuration as the following:

public static IConfigurationRoot Configuration = null;
 public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) // in my case the file name is appsettings.json
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();

        Configuration = builder.Build(); // returns IConfigurationRoot that can be used to access your settings later
    }

Now I am not sure about the static variable I created there it might not be the best way to go about it. But it gave me what I needed.

You can then use it to get your connectionstring like that :

Startup.Configuration["AppSettings:ConnectionString"]

Given that you have a ConnectionString key in your appsettings.json file.

{  
 "AppSettings": 
  {
   "ConnectionString": "" //type your connection string in here 
  }
}

What is even better is to add an AppSettings class like this:

 public class AppSettings
{
    public string ConnectionString { get; set; }
}

Now you need to map it as a service (Adding it to your middleware).

public void ConfigureServices(IServiceCollection services)
    { 
        //other services
        services.Configure<AppSettings> Configuration.GetSection("AppSettings"));
        //other services
    }

So you can inject it to your controllers:

 public class HomeController : Controller
 {
    public _appsettings;
    public HomeController(IOptions<AppSettings> appSettings)
    {
       _appsettings = appSettings;
    }
 }

Finally you can now get your connection string by calling_appsettings.ConnectionString in your controller.

Community
  • 1
  • 1
Mohamed Rozza
  • 567
  • 8
  • 12