在app.config中创建连接字符串attachdbfilename的相对路径

时间:2015-07-01 00:55:57

标签: c# asp.net visual-studio-2013

这是我的EF实体连接字符串,目前AttachDbFile字符串是数据库的完整路径,在部署站点时不起作用。如何为AttachDbFile创建相对路径?

<add name="demoDBEntities" connectionString="metadata=res://*/SalongModel.csdl|res://*/SalongModel.ssdl|res://*/SalongModel.msl;provider=System.Data.SqlClient;provider connection string='data source=(LocalDB)\v11.0;attachdbfilename=&quot;C:\Users\user\Documents\Visual Studio 2013\Projects\WebApplication3\SVCloginLib\App_Data\demoDB.mdf&quot;;integrated security=True;connect timeout=30;MultipleActiveResultSets=True;App=EntityFramework'" providerName="System.Data.EntityClient" />

这是有趣的部分:

attachdbfilename=&quot;C:\Users\user\Documents\Visual Studio 2013\Projects\WebApplication3\SVCloginLib\App_Data\demoDB.mdf&quot;

我向我展示了最明显的一些:

<add name="demoDBEntities" connectionString="metadata=res://*/SalongModel.csdl|res://*/SalongModel.ssdl|res://*/SalongModel.msl;provider=System.Data.SqlClient;provider connection string='data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|demoDB.mdf;integrated security=True;connect timeout=30;MultipleActiveResultSets=True;App=EntityFramework'" providerName="System.Data.EntityClient" />

<add name="demoDBEntities" connectionString="metadata=res://*/SalongModel.csdl|res://*/SalongModel.ssdl|res://*/SalongModel.msl;provider=System.Data.SqlClient;provider connection string='data source=(LocalDB)\v11.0;attachdbfilename=&quot;.\App_Data\demoDB.mdf&quot;;integrated security=True;connect timeout=30;MultipleActiveResultSets=True;App=EntityFramework'" providerName="System.Data.EntityClient" />

<add name="demoDBEntities" connectionString="metadata=res://*/SalongModel.csdl|res://*/SalongModel.ssdl|res://*/SalongModel.msl;provider=System.Data.SqlClient;provider connection string='data source=(LocalDB)\v11.0;attachdbfilename=&quot;~\App_Data\demoDB.mdf&quot;;integrated security=True;connect timeout=30;MultipleActiveResultSets=True;App=EntityFramework'" providerName="System.Data.EntityClient" /> 

加载更多,都给我:

  

底层提供程序在Open上失败。

它用于c#Rest服务,如果它有任何区别

1 个答案:

答案 0 :(得分:1)

您可以使用|DataDirectory|值指定项目中的App_Data文件夹。但是,您需要使用斜杠分隔值:

<add name="demoDBEntities" connectionString="metadata=res://*/SalongModel.csdl|res://*/SalongModel.ssdl|res://*/SalongModel.msl;provider=System.Data.SqlClient;provider connection string='data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\demoDB.mdf;integrated security=True;connect timeout=30;MultipleActiveResultSets=True;App=EntityFramework'" providerName="System.Data.EntityClient" />

您可能还需要在应用程序的初始化方法中设置DataDirectory这样的值(例如Application_Start中的global.asax.cs):

AppDomain.CurrentDomain.SetData("DataDirectory",
    Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));