6

我刚刚创建了一个用户控件。此控件还利用我的静态实体框架类来加载两个组合框。一切都很好,运行没有问题。设计和运行时正在工作。然后,当我停止应用程序时,包含我的 UserControl 的所有表单在设计时都不再工作。我只看到两个错误:

错误 1:在配置中找不到指定的命名连接,不打算与 EntityClient 提供程序一起使用,或者无效。

错误 2:变量ccArtikelVelden未声明或从未赋值。(ccArtikelVelde 是我的UserControl

运行时一切仍在工作

我的静态 EF Repositoy 类:

public class BSManagerData
{
    private static BSManagerEntities _entities;
    public static BSManagerEntities Entities
    {
        get
        {
            if (_entities == null)
                _entities = new BSManagerEntities();
            return _entities;
        }
        set
        {
            _entities = value;
        }
    }
}

在我的 UserControl 中发生了一些逻辑来加载组合框中的数据:

private void LaadCbx()
{
    cbxCategorie.DataSource = (from c in BSManagerData.Entities.Categories
                               select c).ToList();
    cbxCategorie.DisplayMember = "Naam";
    cbxCategorie.ValueMember = "Id";
}

private void cbxCategorie_SelectedIndexChanged(object sender, EventArgs e)
{
    cbxFabrikant.DataSource = from f in BSManagerData.Entities.Fabrikants
                              where f.Categorie.Id == ((Categorie)cbxCategorie.SelectedItem).Id
                              select f;
    cbxFabrikant.DisplayMember = "Naam";
    cbxFabrikant.ValueMember = "Id";
}

让我的表单再次工作的唯一方法是在设计时注释掉 UserControl 中的 EF 部分(见上文)并重建。很奇怪,所有东西都在同一个程序集中,同一个命名空间(为了简单起见)。

任何人的想法?

4

3 回答 3

9

看起来您以某种方式在设计模式下执行数据库代码。为防止这种情况,请查找导致这种情况的控件和方法,并使用:

if (DesignMode)
    return

此外,静态缓存数据库上下文是一个非常糟糕的主意。它会导致多线程问题,以及当您进行插入和删除时。数据库上下文旨在用于单个“工作单元”,添加 2 个,删除 3 个其他对象并调用SaveChanges一次。

于 2010-03-13T16:09:53.877 回答
2

我遇到了同样的问题,

就我而言,我在用户控件加载事件中添加了一些数据库代码,这些代码正在使用一些库,这些库直到运行时才加载。

因此,建议不要在用户控件加载事件中编写任何数据库代码。

希望,这对你有帮助!

于 2011-04-07T05:57:22.363 回答
1

如果您在 userControl 的构造函数上调用函数“LaadCbx()”,则会显示此错误。

因为实体框架的初始化存在于这个函数中。

解决方法是在父窗体的构造函数中调用这个函数“LaadCbx()”。

于 2015-11-08T18:29:58.877 回答