10

I've created a WCF REST service that uses nhibernate to connect to sql server compact edition database. Hence I configure the NHibernate datasource like:

<property name="connection.connection_string">Data Source=[Path]\MyDb.sdf</property>

The annoyance I'm running into now is that I can't figure out how to avoid having to write out the absolute path in the config. This is annoying since I keep the database file as part of the project in the App_Data folder. So I shouldn't have to update the path e.g. when I deploy the project to another location, even if the absolute path is different.

Using procmon I noticed that if I don't write an absolute pat in the Data Source config, it is interpreted as relative to the path: *C:\Program Files (x86)\Common Files\Microsoft Shared\DevServer\10.0*.

Is it possible have nhibernate assume we want to relate the path to the application bin folder instead (which is where my App_Data/MyDb.sdf ends up)?

Diego Mijelshon
  • 52,548
  • 16
  • 116
  • 154
Manolo
  • 1,597
  • 4
  • 21
  • 35

2 Answers2

17

You should use:

Data Source=|DataDirectory|\MyDb.sdf

|DataDirectory| points to the App_Data folder.

Diego Mijelshon
  • 52,548
  • 16
  • 116
  • 154
  • 3
    Just FYI for anyone else you can use this to generate other relatives, ie: `|DataDirectory|\..\bin\File.sdf`. If only I could vote this up more, thanks, perfect. Do you know of any other path keywords the connection string supports or is it just that one? – Paul Tyng Feb 04 '12 at 20:04
  • Worth noting that Paul's tip above does work, despite what has been said on other SO posts. – marc Nov 15 '15 at 01:36
  • Yea, a link to the reference where the keyword definitions are buried would be great... (cite you work) – FizxMike Aug 10 '17 at 15:01
1

Is there any reason why you have your NHibernate configuration in a XML file instead of building the configuration programmatically using the NHibernate configuration interface?

If you have the flexibility, this is how I'd do it:

var path = // dynamically generate your path
var configuration = new Configuration();
configuration.SetProperty(Environment.ConnectionString, String.Format("Data Source={0};", path));
... // other configuration properties

All of the classes you need are under the NHibernate.Cfg namespace. There's also Fluent NHibernate, which provides a much cleaner interface for building your configuration.

Hope that helps!

csano
  • 13,266
  • 2
  • 28
  • 45