【问题标题】:WPF Application ignoring AppDomain.CurrentDomain.SetData valueWPF 应用程序忽略 AppDomain.CurrentDomain.SetData 值
【发布时间】:2013-12-19 22:12:07
【问题描述】:

我有一个解决方案(所有 .NET 4.5 项目),它有一个 Windows 服务、一个 WPF UI 应用程序和一个数据层,其中我有我的 EDMX 模型和一个通用存储库。

当我调试服务时,数据最终存储在数据库中,我希望 UI 在启动时使用相同的数据库文件。

所以我创建了一个这样的目录:

[solution root directory]\Data

我将 MDF 和 LDF 放入其中。我确保我的 EDMX 模型在进行更新等时使用此 MDF 文件。

为了让服务和 UI 使用相同的 MDF 文件,我确保它们的连接字符串使用 |DataDirectory| 符号并在它们都启动时执行此操作:

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

这是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);
}

这会生成 MDF 文件确实所在的确切目录,因此问题不存在,AFAIK。

然而,当我启动 WPF UI 时,我得到了这个错误:

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.

为什么在正确设置|DataDirectory| 之后它仍然试图看那里?反正那里没有 MDF 文件,这就是我目前的打算。

这是 WPF UI 应用的 app.config 中使用的连接字符串:

<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" />

我错过了什么?

谢谢!

编辑:此方法适用于 Windows 服务项目,但不适用于 WPF UI 应用程序。是因为我设置|DataDirectory| 太晚了吗?我还尝试使用 Process Monitor 嗅探某些东西,但我无法获取尝试访问 MDF 的 UI 应用程序:(

【问题讨论】:

    标签: c# .net entity-framework-5 connection-string localdb


    【解决方案1】:

    事实证明我的预感是正确的。在 WPF UI 应用程序中,我在此过程中设置 |DataDirectory| 为时已晚。

    This 解决了这个问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-02
      • 2021-11-12
      • 2016-02-09
      • 1970-01-01
      • 2016-11-11
      相关资源
      最近更新 更多