Home
Options

Getting root of website directory

I am working with an MVC web application project. I have a little snippet of code that generates a .edmx file if my Code First seed process is run (in debug mode only). This code saves the .edmx file in AppDomain.CurrentDomain.BaseDirectory + "/App_Data/" + "foo.edmx". Obviously the appdomain base directory is not my website root directory when using my EF6 dbContext in Linqpad, so it gets an error trying to load my EF context and run my Seed() method.

Is there a proper way to get to my website /App_Data directory (which is rather arbitrary, I just find it a useful place to stash this generated .edmx file) in Linqpad?

The workaround is to build in release mode so that my .edmx generator code is skipped (#if DEBUG), but it's such a pain to flip back and forth all the time.

And before you ask, I'm generating the .edmx file because the diagram is a nice visual, it's not strictly necessary, of course. It's a great way to make sure all my table relationships are set up as intended, etc. And if you're curious, drop this into your Seed():

XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;

using (XmlWriter writer = XmlWriter.Create(
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data", @Model.edmx),
settings))
{
EdmxWriter.WriteEdmx(context, writer);
}
I also have AutomaticMigrationsEnabled = true; on during development which causes my seed method to be called a lot.

Alternatively, now that I think about it, if there was a runtime flag or define that I can use to skip code while running in Linqpad, that would work great!

Comments

  • Options
    Aaaaaagh I'm running into this problem SO MUCH it's making me crazy. Is there a runtime flag I can check to skip code in my code first Seed() function if being called by LinqPad? Or some solution to the AppDomain.CurrentDomain.BaseDirectory problem?
  • Options
    You could check AppDomain.CurrentDomain.FriendlyName. If it contains "LINQPad Query Server", you're running in LINQPad.

  • Options
    Thank you this got me on the right track. It turns out there is yet another appdomain named "custom schema resolver" that is used by LINQPad to get all the context info shown in the left panel after a compile, whereas "LINQPad Query Server" is the name when running an actual query. My fixed code is below:

    //avoids problems with appdomain paths in LINQPad after compiling:
    if (!AppDomain.CurrentDomain.FriendlyName.Contains("Custom schema resolver"))
    {
    XmlWriterSettings settings = new XmlWriterSettings();
    settings.Indent = true;

    using (XmlWriter writer = XmlWriter.Create(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data", @Model.edmx), settings))
    {
    EdmxWriter.WriteEdmx(context, writer);
    }
    }
Sign In or Register to comment.