C# 实体框架连接字符串不是来自配置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9582193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 07:59:33  来源:igfitidea点击:

Entity Framework connection string not from config

c#entity-framework-4connection-string

提问by Wonder

public class Context : DbContext
{
    public Context(string connString) : base(connString) 
    {
        Database.SetInitializer(new MyContextInitializer());
    }
//...

Need to pass a connection string to the context constructor. How should the string look like, for example, for SQL Compact? Tried this, but no success:

需要将连接字符串传递给上下文构造函数。例如,对于 SQL Compact,字符串应该是什么样子的?试过这个,但没有成功:

Context db = new Context("Provider=System.Data.SqlServerCe.4.0;Data Source=D:\Context.sdf");

Edit:

编辑:

If I try this string: "Data Source=D:\\Context.sdf"

如果我尝试这个字符串: "Data Source=D:\\Context.sdf"

System.Data.ProviderIncompatibleException was unhandled

Message=An error occurred while getting provider information from the database.
This can be caused by Entity Framework using an incorrect connection string. Check the inner exceptions for details and ensure that the connection string is correct.

Source=EntityFramework

System.Data.ProviderIncompatibleException 未处理

Message=从数据库获取提供者信息时出错。
这可能是由实体框架使用不正确的连接字符串引起的。检查内部异常以获取详细信息并确保连接字符串正确。

来源=实体框架

And if I try to mention the provider like this: "Data Source=D:\\Context.sdf;provider=System.Data.SqlServerCe.4.0"

如果我尝试像这样提及提供者: "Data Source=D:\\Context.sdf;provider=System.Data.SqlServerCe.4.0"

System.ArgumentException was unhandled

Message=Keyword not supported: 'provider'.

Source=System.Data

System.ArgumentException 未处理

Message=不支持关键字:'provider'。

来源=系统.数据

回答by tanathos

I suggest you to use always the EntityConnectionStringBuilder (System.Data.EntityClient):

我建议您始终使用 EntityConnectionStringBuilder (System.Data.EntityClient):

EntityConnectionStringBuilder ecsb = new EntityConnectionStringBuilder();
ecsb.Provider = "System.Data.SqlServerCe.4.0";
ecsb.Metadata = "..."; // your metadata
ecsb.ProviderConnectionString = "Data Source=D:\Context.sdf";

then you can generate the connection string in a simple way:

那么您可以通过一种简单的方式生成连接字符串:

Context db = new Context(ecsb.ToString());

UPDATE:

更新:

Try to create the EntityConnection, then pass it to the context, instead of connection:

尝试创建 EntityConnection,然后将其传递给上下文,而不是连接:

EntityConnection conn = new EntityConnection(ecsb.ToString());
Context db = new Context(conn);

Anyway, where is the metadata? It's required by the EntityConnection!

无论如何,元数据在哪里?EntityConnection 需要它!

回答by Sander

In my case (exactly the same error) it was solved by changing the default connection factory:

在我的情况下(完全相同的错误)它是通过更改默认连接工厂解决的:

Database.DefaultConnectionFactory = new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0");

Leave out any reference to provider in your connection string because it isn't necessary (this way). I think I read that by default the Database.DefaultConnectionFactory is set to SqlConnectionFactory() but I can't find a reference for that.

在您的连接字符串中省略对 provider 的任何引用,因为它不是必需的(这种方式)。我想我读到默认情况下 Database.DefaultConnectionFactory 设置为 SqlConnectionFactory() 但我找不到参考。

回答by ryanjones

I had a similar error with MVC 4 code first (while running update-database). The error I was getting:

我首先在 MVC 4 代码中遇到了类似的错误(在运行更新数据库时)。我得到的错误:

An error occurred while getting provider information from the database. This can be caused by Entity Framework using an incorrect connection string. Check the inner exceptions for details and ensure that the connection string is correct.

从数据库获取提供者信息时出错。这可能是由实体框架使用不正确的连接字符串引起的。检查内部异常以获取详细信息并确保连接字符串正确。

Turns out that I was missing some crucial information in my web.config to get it all working with localDB. Here's the important sections (I used reference material from http://blogs.msdn.com/b/adonet/archive/2012/01/12/ef-4-3-configuration-file-settings.aspx):

事实证明,我在 web.config 中遗漏了一些关键信息以使其与 localDB 一起工作。以下是重要部分(我使用了来自http://blogs.msdn.com/b/adonet/archive/2012/01/12/ef-4-3-configuration-file-settings.aspx 的参考资料):

<configuration>
  <configSections>
   <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.3.1.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
  </configSections>
  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=ESTdb-01;Integrated Security=true" providerName="System.Data.SqlClient" />
  </connectionStrings>

  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="Data Source=(localdb)\v11.0; Integrated Security=True; MultipleActiveResultSets=True" />
      </parameters>
    </defaultConnectionFactory>
  </entityFramework>
</configuration>

And for good measure, here's my whole web.config (I'm using MVC 4, EF 4.3.1, EF-Migrations):

为了更好地衡量,这是我的整个 web.config(我使用的是 MVC 4、EF 4.3.1、EF-Migrations):

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.3.1.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
  </configSections>
  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=ESTdb-01;Integrated Security=true" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <appSettings>
    <add key="webpages:Version" value="2.0.0.0" />
    <add key="webpages:Enabled" value="true" />
    <add key="PreserveLoginUrl" value="true" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="2880" />
    </authentication>
    <pages>
      <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages" />
      </namespaces>
    </pages>
    <profile defaultProvider="DefaultProfileProvider">
      <providers>
        <add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
      </providers>
    </profile>
    <membership defaultProvider="DefaultMembershipProvider">
      <providers>
        <add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
      </providers>
    </membership>
    <roleManager defaultProvider="DefaultRoleProvider">
      <providers>
        <add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
      </providers>
    </roleManager>
    <sessionState mode="InProc" customProvider="DefaultSessionProvider">
      <providers>
        <add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
      </providers>
    </sessionState>
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules runAllManagedModulesForAllRequests="true" />
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="Data Source=(localdb)\v11.0; Integrated Security=True; MultipleActiveResultSets=True" />
      </parameters>
    </defaultConnectionFactory>
  </entityFramework>
</configuration>

回答by Mai

I had the same problem and it has been solved by:

我遇到了同样的问题,已通过以下方式解决:

1- setting the default project in the manager console to the project that contains the desired web.config

1- 将管理器控制台中的默认项目设置为包含所需 web.config 的项目

2- setting the startup project for the solution to the same project in order for the update command to find the connection string.

2- 将解决方案的启动项目设置为同一项目,以便更新命令找到连接字符串。