用户控件引用Entity Framework

背景:

今天在做软件的时候,出现了问题,我在项目里面添加了Entity Framework,在form的代码里引用没有问题,在userControl里引用就出了问题。

QQ图片20140930165443

我检查app.config文件

QQ图片20140930165450

文件里包含连接字符串,但是就是读取不到

原因:

EF uses the App.Config of the current application. That means that when you're designing the controls inside Visual Studio, it'll use devenv.exe.config. The connection isn't listed there. Also because DB access can have other side-effects (slow down the designer, cause unwanted DB queries), it's best to turn this off at design time.

解释说ef会在设计模式的时候调用app.config文件,但是此时调用的确实vs的配置文件,当然没有我们想要的连接字符串。

解决办法:

在设计的时候不去调用ef即可

代码:

if (DesignMode)
{
    return;
}
using (var edm = new StudentManageEntities())
{
    //do something here
}
 
原文地址:https://www.cnblogs.com/wanghongxu/p/4002317.html