Question

I have a solution (All .NET 4.5 projects) which has a windows service, a WPF UI application and a data layer in which I have my EDMX model and a generic repository.

When I debug the service, data ends up in the database and I want to UI to use the same database file when I launch it.

So I created a directory like such:

[solution root directory]\Data

In which I put the MDF and LDF in. I made sure my EDMX model uses this MDF file when I do updates and such.

For the service and the UI to use the same MDF file, I made sure their connection string use the |DataDirectory| symbol and do this when they both start:

public MainWindow()
{
    string dataDir = Utilities.Utilities.ReturnDataDirectory(System.Reflection.Assembly.GetExecutingAssembly());
    AppDomain.CurrentDomain.SetData("DataDirectory", dataDir);
    InitializeComponent();
    Loaded += MainWindow_Loaded;
}

Here's the code for ReturnDataDirectory:

public static string ReturnDataDirectory(Assembly referingAssembly)
{
    string curDir = referingAssembly.Location;
    string dataDir = string.Empty;
    int x;
    var curDirArray = curDir.Split('\\');

    //Return a directory without the 'Solution.Name\bin\Debug' part...
    for (x = 0; x < (curDirArray.Count() - 4);x++ )
    {
        dataDir += string.Format("{0}\\", curDirArray[x]);
    }

    return string.Format("{0}Data", dataDir);
}

This generates the exact directory where the MDF file indeed resides so the problem is not there, AFAIK.

Yet, when I start the WPF UI, I get this error:

An attempt to attach an auto-named database for file C:\\Dropbox\\My Docs\\MySolution\\MySolution.UI\\bin\\Debug\\MySolution.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.

Why on earth is it still trying to look there after setting |DataDirectory| correctly ? There is no MDF file there anyways, and that's how I intend it for the moment being.

Here is the connection string used in the app.config of the WPF UI ap:

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

What am I missing ?

Thank you!

EDIT: This approach works for the Windows Service project, but not for the WPF UI application. Is it because I'm setting the |DataDirectory| too late ? I also tried sniffing something use Process Monitor, and I can't pickup the UI application trying to access an MDF whatsoever :(

Était-ce utile?

La solution

Turns out my hunch was correct. In the WPF UI application, I was setting |DataDirectory| too late in the process.

This solved the problem.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top