How to correctly move location of .mdf file and change Connection String's DataDirectory accordingly

百般思念 提交于 2019-12-24 07:38:43

问题


Currently my SQL database is on

C:\Users\Slaven\KasaMP.mdf

I want to move it into my projects directory [maybe "database" folder(?)] and make correct changes on my connectionstring. My goal is to be able to open this project with .mdf file attached on any computer. Current ConnectionString I use is EntityFramework generated and I am not sure what is the approach to make this CS point to different location.

ConnectionString:

<connectionStrings>
    <add name="KasaMPEntities" connectionString="metadata=res://*/OsnovniPodaci.Model.csdl|res://*/OsnovniPodaci.Model.ssdl|res://*/OsnovniPodaci.Model.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=(localdb)\v11.0;AttachDbFilename=|DataDirectory|\KasaMP.mdf;initial catalog=KasaMP;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;"
      providerName="System.Data.EntityClient" />
  </connectionStrings>

My projects path:

C:\Users\Slaven\Documents\visual studio 2013\Projects\PCKasa\KasaMP

I found in other posts this following line but I'm not sure what it does:

AppDomain.CurrentDomain.SetData("DataDirectory", System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Database"));

I know I have to place this attribute somewhere in the ConnectionString

AttachDbFileName=|DataDirectory|\KasaMP.mdf

Any suggestions on how to correctly do this? ^ ^


回答1:


In a WinForms application the DataDirectory substitution string point to the folder where the application starts. In case of a Visual Studio session this folder is the BIN\DEBUG or BIN\RELEASE folder (possibly with the x86 variant)

This works well inside Visual Studio but you should be aware that, in your customer PC and without changing the config setting, the folder where you should have the MDF is the same of your app.
But, sadly this location has no write permissions (like C:\program files). An essential requirement for any database app.

So your best bet is to place this file in the CommonApplicationData folder that you can retrieve using Environment.SpecialFolder.CommonApplicationData enum (usually it is C:\PROGRAMDATA in latest version of Windows)

string folder = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
string myAppFolder = Path.Combine(folder, "MyReservedAppDataFolder");
Directory.CreateDirectory(myAppFolder);
AppDomain.CurrentDomain.SetData("DataDirectory", myAppFolder);

All this should be done BEFORE any data access related code in your application. Of course you can leave the setting as it is now without making any change.



来源:https://stackoverflow.com/questions/42199804/how-to-correctly-move-location-of-mdf-file-and-change-connection-strings-datad

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!