为什么我的类库之间无法找到连接字符串?

4
我有如下的体系结构: enter image description here 其中MVC层是表现层。EF是一个类库,而Repository是另一个类库。我试图通过创建EF上下文对象从存储库中插入数据,将EF引用添加到Repository类库中。EF包含edmx文件,其app.config具有由EF生成的连接字符串。 代码如下:
public bool CreateUser(User _user)
   {
       context.Users.Add(_user);
       context.SaveChanges();
       return true;
   }   

但是在执行此操作时,我遇到以下异常:
No connection string named 'MyEntitiesConnection' could be found in the application config file.

我尝试在存储库的app.config中添加相同名称的连接字符串,但没有起作用。有人有解决方法吗? 编辑: 连接字符串为:
<add name="MyEntitiesConnection" connectionString="metadata=res://*/EF.Entities.csdl|res://*/EF.Entities.ssdl|res://*/EF.Entities.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=Servername\MSSQL2008R2;initial catalog=MyDBName;persist security info=True;user id=sa;MultipleActiveResultSets=True;App=EntityFramework;" providerName="System.Data.EntityClient" />

app.config:

<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
    <connectionStrings>
        <add name="MyEntitiesConnection" connectionString="metadata=res://*/EF.Entities.csdl|res://*/EF.Entities.ssdl|res://*/EF.Entities.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=Servername\MSSQL2008R2;initial catalog=MyDBName;persist security info=True;user id=sa;MultipleActiveResultSets=True;App=EntityFramework;" providerName="System.Data.EntityClient" />
    </connectionStrings>    
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
  </entityFramework>
</configuration>

展示给我们配置。 - Ant P
谢谢,这里需要放置哪个配置? - Red Swan
包含连接字符串的配置。 - Ant P
1个回答

2
在任何.NET应用程序中,只有一个配置文件是查找配置信息的自然起点。对于Web应用程序来说,这是位于应用程序根目录下的web.config文件。
尽管你的存储库项目(实际上,一些VS工具可能已经添加了一个)或EF项目中可能有一个名为app.config的文件,但在尝试读取配置信息时不会使用它。
连接字符串部分需要存在于你的MVC应用程序的web.config中。
对于非Web应用程序,它是生成.exe文件的项目的app.config,并且在构建过程中自动复制为XXX.exe.config

好的,这是否意味着我不能在单独的类库中使用EF?因为如果我们想要在层之间使用EF作为dll? - Red Swan
1
你可以将它用于一个独立的类库中。但是,你必须将连接字符串信息复制到使用该类库的应用程序的 web.config 文件中。类库不会有自己独立的 config 文件。 - Damien_The_Unbeliever
这就是我在Repository项目中使用EF dll。我尝试在Repository的app.config中添加相同的连接字符串,但出现了相同的问题。 - Red Swan
我不知道该怎么说了。类库项目中的 app.config 文件是没有意义的,只有 web.config 文件才是重要的。 - Damien_The_Unbeliever
不需要。那些你在类库项目中拥有的 app.config 文件是没有意义的。它们根本没有被使用。无论你是在主应用程序项目还是在类库代码中访问配置,读取的配置文件都是应用程序的配置文件 - 对于 Web 应用程序是 web.config,对于其他类型的应用程序是 XXX.exe.config 文件。只需将连接信息放入 MVC 应用程序的 web.config 文件中,你会发现错误消失了。 - Damien_The_Unbeliever
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接