Search code examples
sql-server-ceconnection-string

The path is not valid for SqlServerCe


I have two projects:

1 - "Domain" with SqlCe database in 'Repositories' folder

2 - "Web" mvc4 project

The connection string in 'Domain' project in app.config looks like this (it was created automatically by wizard):

    <connectionStrings>
        <add name="Domain.Properties.Settings.MyDbConnectionString"
          connectionString="Data Source=|DataDirectory|\Repositories\MyDb.sdf"
          providerName="Microsoft.SqlServerCe.Client.4.0" />
   </connectionStrings>

I've copy-pasted this to web.config of 'Web' project:

<connectionStrings>
    <add name="Domain.Properties.Settings.MyDbDbConnectionString"
      connectionString="Data Source=\Repositories\MyDb.sdf"
      providerName="Microsoft.SqlServerCe.Client.4.0" />
  </connectionStrings>

When I run the 'Web' application it throws exception:

The path is not valid. Check the directory for the database. [ Path = \Repositories\MyDb.sdf ]

This path exists in bin directory of 'Web' project. What's is wrong here?

I could make it work with this in the code:

var connectionString = ("Data Source=" + System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetAssembly(typeof(DbRepository)).GetName().CodeBase) + "\\Repositories\\GameStoreDb.sdf").Replace("file:\\", string.Empty);

But it's sure a very dirty workaround ). What is the correct way of specifying connection string?


Solution

  • Your code based solution is perfectly fine and valid