如何正确移动.mdf文件的位置并相应地更改连接字符串的DataDirectory

时间:2017-02-13 08:41:51

标签: c# sql-server winforms entity-framework connection-string

目前我的SQL数据库已经开启

C:\Users\Slaven\KasaMP.mdf

我想将它移动到我的项目目录[也许是“数据库”文件夹(?)]并对我的connectionstring进行正确的更改。 我的目标是能够使用附加在任何计算机上的.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 个答案:

答案 0 :(得分:2)

在WinForms应用程序中,DataDirectory替换字符串指向应用程序启动的文件夹。在Visual Studio会话的情况下,此文件夹是BIN \ DEBUG或BIN \ RELEASE文件夹(可能使用x86变体)

这在Visual Studio中运行良好,但您应该知道,在您的客户PC中并且不更改配置设置,您应该拥有MDF的文件夹与您的应用程序相同。
但是,遗憾的是这个位置没有写权限(比如C:\ program files)。任何数据库应用程序的基本要求。

所以最好的办法是将此文件放在CommonApplicationData文件夹中,您可以使用Environment.SpecialFolder.CommonApplicationData枚举检索该文件夹 (通常在最新版本的Windows中是C:\ PROGRAMDATA)

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

所有这些都应该在您的应用程序中的任何数据访问相关代码之前完成。 当然,您可以保留现在的设置而不做任何更改。