我使用实体框架和ASP。NET MVC 4构建应用程序

我的解决方案分为两个项目;

一个类库,其中包括我的数据模型(.edmx)文件和一些自定义接口 引用上面类库的“容器”MVC项目

我的问题是,当我试图使用'MyEntites' DbContext时,我得到以下错误:

中找不到名为“MyEntities”的连接字符串 应用程序配置文件。

我猜这个问题与连接字符串位于类库的app.config而不是MVC项目的事实有关。

有人有什么建议吗?


当前回答

这是因为您的上下文类是从DbContext继承的。我猜你的上司是这样的:

public MyEntities()
    : base("name=MyEntities")

name =…应该改为你的connectionString的名字

其他回答

我刚刚发现的解决这个问题的最好方法是临时将该项目(很可能是一个类库)设置为启动项目。这将强制包管理器控制台使用该项目作为它的配置源。这样设置的部分原因是配置文件通常遵循的自顶向下模型。经验法则是,最接近客户端的项目(例如MVC应用程序)是web。将使用的Config或app.config。

是的,这很愚蠢。使用连接构建器可以避免复制连接字符串。VB。Net代码(在生产中使用,但在这里略有修改,因此视为未经测试,乐意协助解决任何问题),其中我有一个serverName变量,一个databaseName变量,我将它们传递到一个方法,并让它为我生成连接:

    Dim EfBuilder As New System.Data.EntityClient.EntityConnectionStringBuilder("metadata=res://*/VMware.VmEf.csdl|res://*/VMware.VmEf.ssdl|res://*/VMware.VmEf.msl;provider=System.Data.SqlClient;provider connection string=""data source=none;initial catalog=none;integrated security=True;multipleactiveresultsets=True;App=EntityFramework""")
   Dim SqlBuilder As New Data.SqlClient.SqlConnectionStringBuilder(EfBuilder.ProviderConnectionString)
                        SqlBuilder.DataSource = serverName
                        SqlBuilder.InitialCatalog = databaseName
                        EfBuilder.ProviderConnectionString = SqlBuilder.ConnectionString
                        Using vmCtx As New VmEfConn(EfBuilder.ConnectionString)

你是对的,这是因为类库(其中.edmx文件)不是你的启动/主项目。

您需要将连接字符串复制到主项目配置文件。

如果你的启动/主项目没有配置文件(就像在我的控制台应用程序的情况下),只需添加一个(启动项目-添加新项->应用程序配置文件)。

更多相关信息可以在这里找到: MetadataException:无法加载指定的元数据资源

Add an App.Config file Set the project as startup project. Make sure you add the connection strings after entityFramework section: <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=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/> </configSections> <connectionStrings> <!-- your connection string goes here, after configSection --> </connectionString>

正如您所猜测的,这与类库的app.config中的连接字符串有关。

将类app.config中的条目复制到容器的app.config或web中。配置文件