How do I properly set the DataDirectory in a web project connection string?

放肆的年华 提交于 2019-12-23 12:24:17

问题


My solution has a class lib project with a database (my DAL), and a web project to act as a WCF service layer.

I add a reference to the DAL project from the web project, and when I compile, my database is copied to the Bin folder of the web project.

The Web.config file needs the connection string. If I use:

attachdbfilename=|DataDirectory|\Test.mdf

it looks for the DB in the App_Data folder.

I can easily place a copy of the DB in the App_Data folder, however, at this stage in development I'm making frequent changes to the schema (via the copy in the DAL), and would like the project to pickup the version copied to the WCF layers bin folder.

I know I can alter the default DataDirecty with this:

AppDomain.CurrentDomain.SetData("DataDirectory", path);

A) Without using a hard-coded absolute path, is there a better way to get the connection string to use the bin folder?

B) If I do alter the default DataDirectory setting, how do I programmatically obtain the absolute reference to the bin folder?

<Rant> Shouldn't Visual Studio 2010 have been smart enough to realize the project types and instead of pulling the DB from the referenced assembly into the bin folder, used the App_Data folder instead? </Rant>


回答1:


In your web project you should be able to find the path by doing:

string path = Server.MapPath("~/bin/Test.mdf");

You can then set the path in Application_Start in your Global.ascx.cs

AppDomain.CurrentDomain.SetData("DataDirectory", path);

I realise this answers part B of your question but not part A.



来源:https://stackoverflow.com/questions/6682940/how-do-i-properly-set-the-datadirectory-in-a-web-project-connection-string

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