简体   繁体   English

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

[英]No connection string named 'MyEntities' could be found in the application config file

I am using entity framework and ASP.NET MVC 4 to build an application我正在使用实体框架和 ASP.NET MVC 4 来构建应用程序

My solution is split into two projects;我的解决方案分为两个项目;

  • A class library that includes my data model (.edmx) file and a few custom interfaces包含我的数据模型 (.edmx) 文件和一些自定义接口的类库
  • The 'container' MVC project that references the class library above引用上述类库的“容器”MVC 项目

My problem is that when I attempt to use the 'MyEntites' DbContext I get the the following error:我的问题是,当我尝试使用“MyEntites” DbContext 时,出现以下错误:

No connection string named 'MyEntities' could be found in the application config file.在应用程序配置文件中找不到名为“MyEntities”的连接字符串。

I guess the problem has something to do with the fact that connection string lies within the app.config of the class library rather than the MVC project.我猜这个问题与连接字符串位于类库的 app.config 而不是 MVC 项目中的事实有关。

Does anyone have any suggestions?有没有人有什么建议?

尝试将连接字符串复制到 MVC 项目中的 .config 文件。

You are right, this happens because the class library (where the .edmx file) is not your startup / main project.您说得对,这是因为类库(.edmx 文件所在的位置)不是您的启动/主项目。

You'll need to copy the connection string to the main project config file.您需要将连接字符串复制到主项目配置文件中。

Incase your startup / main project does not have a config file (like it was in my Console Application case) just add one (Startup project - Add New Item -> Application Configuration File).如果您的启动/主项目没有配置文件(就像在我的控制台应用程序案例中一样),只需添加一个(启动项目 - 添加新项目 -> 应用程序配置文件)。

More relevant information can be found here: MetadataException: Unable to load the specified metadata resource更多相关信息可以在这里找到: MetadataException:无法加载指定的元数据资源

make sure that you make your project (with the DbContext) as startup确保将项目(使用 DbContext)设为启动

在项目上右键单击并选择

OR要么

Add to the project that is set as startup your connection string in the app.config (or web.config)在 app.config(或 web.config)中添加到设置为启动你的连接字符串的项目

OR要么

Call the command like this像这样调用命令

Update-Database -Script -ProjectName '<project name>' -StartupProjectName '<project name>' -ConnectionString 'data source=.;initial catalog=<db name>;integrated security=True;MultipleActiveResultSets=True' -ConnectionProviderName 'System.Data.SqlClient'

Then try again然后再试一次

You could just pass the connection string to EntityFramework and get on with your life:您可以将连接字符串传递给EntityFramework并继续您的生活:

public partial class UtilityContext : DbContext
{
    static UtilityContext()
    {
        Database.SetInitializer<UtilityContext>(null);
    }

    public UtilityContext()
        : base("Data Source=SERVER;Initial Catalog=DATABASE;Persist Security Info=True;User ID=USERNAME;Password=PASSWORD;MultipleActiveResultSets=True")
    {
    }

    // DbSet, OnModelCreating, etc...
}

As you surmise, it is to do with the connection string being in app.config of the class library.正如您猜测的那样,这与类库的 app.config 中的连接字符串有关。

Copy the entry from the class app.config to the container's app.config or web.config file将 app.config 类中的条目复制到容器的app.configweb.config文件中

如果您在解决方案中有多个项目,那么在您拥有真实 App.config 的地方开始设置项目。

将连接字符串复制到已设置为“设置为StartUp项目”的项目中的app.configweb.config文件,如果在数据层项目中使用实体框架 - 请在主项目中安装实体框架 nuget

  1. Add an App.Config file添加 App.Config 文件
  2. Set the project as startup project.将项目设置为启动项目。
  3. Make sure you add the connection strings after entityFramework section:确保在entityFramework部分之后添加连接字符串:

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

It also happens if the startup project is changed to the one, which does not have the connection strings .如果将启动项目更改没有连接字符串的项目,也会发生这种情况。

  1. Right Click Solution - click properties右键单击解决方案-单击属性
  2. Under Common Properties,select startup project在 Common Properties 下,选择启动项目
  3. On the right pane select the project which has the connection strings (in most cases, it will be MVC projects - the project that starts the solution)在右侧窗格中选择具有连接字符串的项目(在大多数情况下,它将是 MVC 项目 - 启动解决方案的项目)

Yeah, it's silly.是的,这很愚蠢。 You can avoid copying the connection string by using a connection builder.您可以使用连接构建器来避免复制连接字符串。 VB.Net code (used in production, but slightly modified here, so treat as untested, happy to assist with any issues), where I have a serverName variable, a databaseName variable, I pass them into a method and have it generate the connection for me: 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)

are you using more than one project on your solution?您是否在解决方案中使用了多个项目?

Because if you are, the web config you must check is the one on the same project as de .edmx file因为如果是,则必须检查的 web 配置与 de .edmx 文件位于同一项目中

It is because your context class is being inherited from DbContext.这是因为您的上下文类是从 DbContext 继承的。 I guess your ctor is like this:我猜你的 ctor 是这样的:

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

name=... should be changed to your connectionString's name name=...应该更改为您的 connectionString 的名称

将 ConnectionString 添加到 MVC Project Web.config 文件

I've had this problem when I use multiple proyects, the start proyect with web.config and app.config for EntityFramework project.当我使用多个项目时,我遇到了这个问题,即 EntityFramework 项目的 web.config 和 app.config 启动项目。

for avoid this problem you must:为了避免这个问题,你必须:

  1. You need the connection string in the started *.config file.您需要启动的 *.config 文件中的连接字符串。
  2. You need have installed the EntityFramework DLL into your references您需要已将 EntityFramework DLL 安装到您的引用中

I have faced the same issue.我遇到了同样的问题。 I was missed to put connection string to startup project as I am performing data access operation from other layer.当我从其他层执行数据访问操作时,我错过了将连接字符串放入启动项目的过程。 also if you don't have app.config in your startup project then add app.config file and then add a connection string to that config file.此外,如果您的启动项目中没有 app.config,则添加 app.config 文件,然后将连接字符串添加到该配置文件中。

I got this by not having the project set as startup, as indicated by another answer.如另一个答案所示,我没有将项目设置为启动,这是我得到的。 My contribution to this - when doing Add-Migrations and Update-Database, specify the startup project as part of the command in Nuget Package Manager Console (do not include the '[' or ']' characters, that's just to show you that you need to change the text located there to your project name):我对此的贡献 - 在执行 Add-Migrations 和 Update-Database 时,将启动项目指定为 Nuget 包管理器控制台中命令的一部分(不要包含 '[' 或 ']' 字符,这只是为了向您展示您需要将位于那里的文本更改为您的项目名称):

  1. Enable-Migrations启用迁移
  2. Add-Migrations -StartupProject [your project name that contains the data context class] Add-Migrations -StartupProject [包含数据上下文类的项目名称]
  3. Update-Database -StartupProject [same project name as above] Update-Database -StartupProject [与上面相同的项目名称]

That should do it.那应该这样做。

The connection string generated by the project containing the .edmx file generates the connection string, this would appear to be a holdover from the app.config sorts of files that were copied to the output directory and referenced by the executable to store runtime config information.包含 .edmx 文件的项目生成的连接字符串生成连接字符串,这似乎是 app.config 类型文件的保留,这些文件已复制到输出目录并由可执行文件引用以存储运行时配置信息。

This breaks in the web project as there is no automatic process to add random .config information into the web.config file for the web project.这会在 web 项目中中断,因为没有自动过程将随机 .config 信息添加到 web 项目的 web.config 文件中。

Easiest is to copy the connection string from the config file to the connections section of the web.config file and disregard the config file contents.最简单的方法是将连接字符串从配置文件复制到 web.config 文件的连接部分并忽略配置文件内容。

The best way I just found to address this is to temporarily set that project (most likely a class library) to the startup project.我刚刚发现解决这个问题的最好方法是暂时将该项目(很可能是一个类库)设置为启动项目。 This forces the package manager console to use that project as it's config source.这会强制包管理器控制台使用该项目作为其配置源。 part of the reason it is set up this way is because of the top down model that th econfig files usually follow.以这种方式设置的部分原因是 econfig 文件通常遵循自上而下的模型。 The rule of thumb is that the project that is closest to the client (MVC application for instance) is the web.config or app.config that will be used.经验法则是最接近客户端的项目(例如 MVC 应用程序)是将使用的 web.config 或 app.config。

Make sure you've placed the connection string in the startup project's ROOT web.config.确保您已将连接字符串放在启动项目的 ROOT web.config 中。

I know I'm kinda stating the obvious here, but it happened to me too - though I already HAD the connection string in my MVC project's Web.Config (the .edmx file was placed at a different, class library project) and I couldn't figure out why I keep getting an exception... Long story short, I copied the connection string to the Views\\Web.Config by mistake, in a strange combination of tiredness and not-scrolling-to-the-bottom-of-the-solution-explorer scenario.我知道我在这里说的很明显,但它也发生在我身上 - 尽管我已经在我的 MVC 项目的 Web.Config 中拥有连接字符串(.edmx 文件被放置在不同的类库项目中)并且我不能不知道为什么我总是收到异常...长话短说,我错误地将连接字符串复制到了 Views\\Web.Config,这是一种疲倦和不滚动到底部的奇怪组合-解决方案浏览器场景。 Yeah, these things happen to veteran developers as well :)是的,这些事情也发生在资深开发人员身上 :)

This problem happen when you are using Layers in your Project and defined or install Entity frame work in DataLayer and try to run your Project当您在项目中使用图层并在 DataLayer 中定义或安装实体框架并尝试运行您的项目时,会发生此问题

So to overcome from this problem copy the connection string from the layer where the Edmx file is there and paste the connection string in main web.config.因此,为了解决这个问题,从 Edmx 文件所在的层复制连接字符串,并将连接字符串粘贴到主 web.config 中。

Add a connection string in the root web.config file of 'container' MVC project that references the class library as following:在 'container' MVC 项目的根 web.config 文件中添加一个引用类库的连接字符串,如下所示:

 <connectionStrings>

  <add name="MyEntities" connectionString="complete connection string here" providerName="System.Data.SqlClient" />

  </connectionStrings>

If you do not want to use "MyEntities" as connection name then change it as you wish but make the following change in your MyEntities DbContext class:如果您不想使用“MyEntities”作为连接名称,请根据需要进行更改,但在 MyEntities DbContext 类中进行以下更改:

MyEntities: DbContext
 {
   public MyEntities():base("Name-Of-connection-string-you wish to connect"){ }
 }

Reason for this error is, If we will not specify the name of connection string Or connect string in derived class of DbConext(In your case it is MyEntities) then DbContext will automatically search for a connection string in root web.config file whoes name is same as derived class name (In your case it is My Entities).此错误的原因是,如果我们不会在 DbConext 的派生类中指定连接字符串的名称或连接字符串(在您的情况下是 MyEntities),则 DbContext 将自动在根 web.config 文件中搜索名称为的连接字符串与派生类名称相同(在您的情况下,它是我的实体)。

I had this problem when running MSTest.我在运行 MSTest 时遇到了这个问题。 I could not get it to work without the "noisolation" flag.没有“噪音隔离”标志,我无法让它工作。

Hopefully this helps someone.希望这有助于某人。 Cost me a lot of time to figure that out.我花了很多时间来弄清楚这一点。 Everything ran fine from the IDE.从 IDE 中一切正常。 Something weird about the Entity Framework in this context.在这种情况下,实体框架有些奇怪。

Regular migrations定期迁移

There are two options - the first one that everyone here has suggested is to ensure that the connection string is in the Web.config file of the project.有两个选项 - 这里每个人都建议的第一个选项是确保连接字符串在项目的 Web.config 文件中。 When working with connection strings from Azure application settings, that means overwriting your Web.config values with the Azure values.使用 Azure 应用程序设置中的连接字符串时,这意味着用 Azure 值覆盖您的 Web.config 值。

Azure or automatic migrations (programmatic) Azure 或自动迁移(程序化)

There's a second option available if you're running migrations programmatically, that allows you to run migrations using a connection string that's obtained dynamically (or via Azure application settings) without storing it in Web.config:如果您以编程方式运行迁移,则有第二个选项可用,它允许您使用动态(或通过 Azure 应用程序设置)获取的连接字符串运行迁移,而无需将其存储在 Web.config 中:

When setting the configuration's TargetDatabase , use the DbConnectionInfo constructor that takes a connection string and a provider name instead of the constructor that takes just a connection name.设置配置的TargetDatabase 时,请使用采用连接字符串和提供程序名称的DbConnectionInfo构造函数,而不是仅采用连接名称的构造函数。 If your connection string doesn't have a provider name and you're using SQL Server / Azure SQL then use "System.Data.SqlClient"如果您的连接字符串没有提供程序名称并且您使用的是 SQL Server/Azure SQL,则使用“System.Data.SqlClient”

This could also result in not enough dll references being referenced in the calling code.这也可能导致在调用代码中引用的 dll 引用不足。 A small clumsy hack could save your day.一个小小的笨拙的黑客可以拯救你的一天。

I was following the DB First approach and had created the EDMX file in the DAL Class library project, and this was having reference to the BAL Class library, which in turn was referenced by a WCF service.我遵循 DB First 方法并在 DAL 类库项目中创建了 EDMX 文件,这是对 BAL 类库的引用,而 BAL 类库又被 WCF 服务引用。

Since I was getting this error in the BAL, I had tried the above mentioned method to copy the config details from the App.config of the DAL project, but didn't solve.由于我在 BAL 中收到此错误,因此我尝试了上述方法从 DAL 项目的 App.config 中复制配置详细信息,但没有解决。 Ultimately with the tip of a friend I just added a dummy EDMX file to the WCF project (with relevant DB Connectivity etc), so it imported everything necessary, and then I just deleted the EDMX file, and it just got rid of the issue with a clean build.最终,在朋友的提示下,我刚刚向 WCF 项目添加了一个虚拟 EDMX 文件(具有相关的数据库连接等),因此它导入了所有必要的东西,然后我只是删除了 EDMX 文件,它刚刚摆脱了这个问题一个干净的构建。

There is a comment on the top answer by @RyanMann that suggests: @RyanMann对最佳答案的评论表明:

Store your connection strings in one config file, then reference them in other projects by <connectionString configSource="../ProjectDir/SharedConnections.config" />将您的连接字符串存储在一个配置文件中,然后通过<connectionString configSource="../ProjectDir/SharedConnections.config" />在其他项目中引用它们

This is a fantastic suggestion!这是一个绝妙的建议!

It also works to share connection strings between App.config and Web.config files!它还可以在 App.config 和 Web.config 文件之间共享连接字符串!

Anyone wanting to follow this suggestion, should head on over to this SO answer .任何想要遵循此建议的人,都应该转到这个 SO 答案 It has a really great step-by-step guide on sharing connection strings among multiple projects in a solution.它有一个非常棒的分步指南,可以在解决方案中的多个项目之间共享连接字符串。

The only caveat is that configSource must exist in the same directory or a sub-directory.唯一需要注意的是configSource必须存在于同一目录或子目录中。 The link above explains how to use "Add as Link" to get around this.上面的链接解释了如何使用“添加为链接”来解决这个问题。

I had this error when attempting to use EF within an AutoCAD plugin.尝试在 AutoCAD 插件中使用 EF 时出现此错误。 CAD plugins get the connection string from the acad.exe.config file. CAD 插件从 acad.exe.config 文件中获取连接字符串。 Add the connect string as mentioned above to the acad config file and it works.将上面提到的连接字符串添加到 acad 配置文件中,它就可以工作了。

Credit goes to Norman.Yuan from ADN.Network.归功于 ADN.Network 的 Norman.Yuan。

If you are using an MVVM model, try to copy the connection strings to all parts of your project.如果您使用的是 MVVM 模型,请尝试将连接字符串复制到项目的所有部分。

For example, if your solution contains two projects, the class library project and the wpf project, you must copy the connection strings of the backend project (library class porject) and place a copy in the App.config file of the wpf project.例如,如果您的解决方案包含类库项目和wpf 项目两个项目,则必须复制后端项目(库类项目)的连接字符串,并在wpf 项目的App.config 文件中放置一个副本。

<connectionStrings>
  <add name="DBEntities" ... />
</connectionStrings>

Hope it's helpful for you :)希望对你有帮助:)

在 web.config 文件中添加 Connectoinstrnig

<ConnectionStiring> <add name="dbName" Connectionstring=" include provider name too"  ></ConnectionStiring>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 '在应用程序配置文件中找不到名为'MyEntities'的连接字符串。' - 'No connection string named 'MyEntities' could be found in the application config file.' 在应用程序配置文件中找不到名为“ CREntities”的连接字符串 - No connection string named 'CREntities' could be found in the application config file 在应用程序配置文件中找不到名为“thenameofmyconnection”的连接字符串 - No connection string named “thenameofmyconnection” could be found in the application config file 在应用程序配置文件中找不到名为“ KgSoftProContext”的连接字符串 - No connection string named 'KgSoftProContext' could be found in the application config file InvalidOperationException:在应用程序配置文件中找不到名为“PayMyRentEntities”的连接字符串 - InvalidOperationException: No connection string named 'PayMyRentEntities' could be found in the application config file 在应用程序配置文件中找不到已命名的连接字符串 - No connection string named could be found in the application config file 在应用程序配置文件中找不到名为“CarAccountingEntities”的连接字符串 - No connection string named 'CarAccountingEntities' could be found in the application config file 具有EF6的C#插件-在应用程序配置文件中找不到名为“实体”的连接字符串 - C# addin with EF6 - No connection string named 'Entities' could be found in the application config file 使用EF6的WCF - 在应用程序配置文件中找不到名为“Entities”的连接字符串,[I SET IT] - WCF with EF6 - No connection string named 'Entities' could be found in the application config file , [I SET IT] 具有实体框架的ASP.NET Core 2,在应用程序配置文件中找不到名为“ ####”的连接字符串 - ASP.NET Core 2 with Entity Framework, showing no connection string named '####' could be found in the application config file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM