Make the connectionstring's AttachDbFilename relative in config file

谁说我不能喝 提交于 2019-12-10 10:48:12

问题


I am working on a project using an mdf file generated locally using Entity Framework Code First. The path to this mdf is set in several config files in my solution using <connectionStrings> sections like so :

<add name="DataContext" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=&quot;E:\path\to\project\app_data\local.mdf&quot;;Integrated Security=True" providerName="System.Data.SqlClient" />

I use git versionning on this project both from work and at home, thus at work the mdf filepath has to be E:\path\to\project\app_data\local.mdf\ and at home D:\otherpath\to\project\app_data\local.mdf.

This is painful to change everytime I comute (first world problem, I know).

I have seen how to set a substitution string but this seems to be using code outside the config file and I don't want that. Maybe there is a way to set a relative |DataDirectory| value inside the config file ?

Can I make this path relative to a unique place next to my .sln file, using only those config files ?

This would ideally be something like that :

<add name="DataContext" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=&quot;|RelativeToWorkplaceDynamicPath|\local.mdf&quot;;Integrated Security=True" providerName="System.Data.SqlClient" />

Thanks.


回答1:


I think I figured out how to make this work.

I explain in detail at: How to embed a database in a visual studio solution?

In short, you start your connection string with the substitution string "|DataDirectory|". And then you set your current AppDomain's "DataDirectory" setting to where you want it to be, before you access the database.

It's not perfectly clean, but it's workable.



来源:https://stackoverflow.com/questions/24008830/make-the-connectionstrings-attachdbfilename-relative-in-config-file

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