2017-02-13 52 views
1

目前我的SQL數據庫上如何正確地移動.mdf文件和更改連接字符串的DataDirectory目錄相應

C:\Users\Slaven\KasaMP.mdf 

我想將其移動到我的項目目錄的位置[也許「數據庫」文件夾(?)]並對連接字符串進行正確的更改。 我的目標是能夠在任何計算機上附加.mdf文件來打開此項目。我使用的當前ConnectionString是EntityFramework生成的,我不確定將該CS指向不同位置的方法是什麼。

的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> 

我的項目路徑:

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

我在其他帖子這下面一行找到,但我不知道它做什麼:

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

我知道我必須將這個屬性放在ConnectionString的某個地方

AttachDbFileName=|DataDirectory|\KasaMP.mdf 

有關如何正確執行此操作的任何建議?^^

回答

1

在WinForms應用程序中,DataDirectory替換字符串指向應用程序啓動的文件夾。如果是Visual Studio會話,此文件夾是BIN \ DEBUG或BIN \ RELEASE文件夾(可能爲x86變體)

這適用於Visual Studio,但您應該知道,在您的客戶PC中並且不會更改配置設置,您應該擁有MDF的文件夾與您的應用程序相同。
但是,遺憾的是,這個位置沒有寫權限(如C:\程序文件)。任何數據庫應用程序的基本要求。

所以最好的辦法是把在CommonApplicationData文件夾這個文件,你可以檢索使用Environment.SpecialFolder.CommonApplicationData枚舉 (通常是C:\ PROGRAMDATA在最新版本的Windows)

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

這一切都應該是在應用程序中的任何與數據訪問相關的代碼之前完成。 當然,您可以保留現在的設置而不做任何更改。

+0

感謝您的建議,但我不知道如何更改.mdf的位置從我的SQL Server xD – ChenChi

+0

我試過這個:https://blog.sqlauthority.com/2012/10/28/sql-server- move-database-files-mdf-and -ldf-to-another-location /但我得到了一堆錯誤 – ChenChi

+1

我不明白。您的配置文件使用LocalDb實例。您是否告訴我您的客戶使用已安裝的Sql Server或Sql Server Express實例?在這種情況下,連接字符串是完全不同的,你需要添加你的MDF文件到Sql Server的已安裝實例 – Steve

相關問題