简体   繁体   English

实体框架抛出无效操作异常 - 找不到app.config中的连接字符串

[英]Entity framework throwing invalid operation exception - Connection string in app.config not found

I added a new ADO.NET data model from the database, and everything generated fine. 我从数据库中添加了一个新的ADO.NET数据模型,一切都很好。

Then I try to make a call to get one of the tables: 然后我尝试调用以获取其中一个表:

public Sensor[] GetAllRegisteredSensors()
        {
            using (var context = new ClientSensorLocationEntities())
            {
                try
                {
                    return context.Sensors.ToArray();

                }
                catch (Exception ex)
                {
                    throw;
                }
            }
        }

and I get an exception: 我得到一个例外:

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

Pretty self-explanatory and then I went to my app.config file which looks like this: 非常不言自明,然后我去了我的app.config文件,看起来像这样:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
    <add name="ClientSensorLocationEntities" connectionString="metadata=res://*/ClientSensorLocationModel.csdl|res://*/ClientSensorLocationModel.ssdl|res://*/ClientSensorLocationModel.msl;
               provider=System.Data.SqlClient;provider connection string=&quot;data source=MYUSER\SQLEXPRESS;initial catalog=ClientSensorLocation;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;"
               providerName="System.Data.EntityClient" />
              </connectionStrings>
              <startup>
                <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" />
          </startup>
        </configuration>

So the connection string with that name exists. 因此存在具有该名称的连接字符串。 What seems to be the problem then? 那似乎是什么问题呢?

If you are using DbContext from referencing Projects, you also need to register the connection string on the project configuration file. 如果您在引用Projects时使用DbContext ,则还需要在项目配置文件中注册连接字符串。

For example, if you are using the DbContext on a web project, check if the connection string is on the web.config. 例如,如果您在Web项目上使用DbContext ,请检查连接字符串是否在web.config上。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM