Entity Framework DbContext Connection string in app.config/web.config not being seen

与世无争的帅哥 提交于 2019-12-11 03:56:12

问题


So, I have followed this instruction from ADO.NET team blog to try to make a small test project. I have double-checked everything. It doesn't seem to work and keeps saying connection string is missing.

http://blogs.msdn.com/b/adonet/archive/2011/03/15/ef-4-1-model-amp-database-first-walkthrough.aspx

Step. 1 Build this UserModels.dll. In the dll, App.Config file, edmx generated this connection string: (hit the 'test' button when making it, and it connects successfully, and generated the edmx diagram of all the tables from 'UserDatabase')

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
    <add name="UserModelsContainer" connectionString="metadata=res://*/UserModels.csdl|res://*/UserModels.ssdl|res://*/UserModels.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=MyDesktop\SQL2008;initial catalog=UserDatabase;integrated security=True;multipleactiveresultsets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>
</configuration>

Step 2. Then I made a test project:

class UnitTetst1 ....
TestMethod1()....
using (var db = new UserModelsContainer()) {
  int i = db.Users.Count(); // <---expecting '0' for a new db, but I get an exception
}

---------PROBLEM HERE -----------------

Step 3. Run the test. Then I get an error InvalidOperationException like this:

"No connection string named 'UserModelsContainer' could be found in the application config file."

Seems like DbContext doesn't know where to pick up the connectionStrings from App.Config??

Please help~~


回答1:


When running a program, it's the app.config of the .exe file being run that is read. The app.config of the .dll is never used. Since UserModel.dll is a dll, there must be an .exe (or web site) somewhere that you run. Place the connection string in that exe's app.config (or if it is a web site in the web.config).




回答2:


I had this issue when I was attempting to do an update-database command from the "package manger console". I had a separate project for my code first Data access layer and another for my web project, etc

I was using the following command: "update-database -projectname MYPROJECTDANAME -CONNECTIONSTRINGNAME CONNECTIONSTRING -Force"

so it pointed at my MYPROJECTDANAME project however it takes the connectionstring name from startup project you have specified. Therefore make sure the project you have marked as the startup project has the required connection string.



来源:https://stackoverflow.com/questions/10772108/entity-framework-dbcontext-connection-string-in-app-config-web-config-not-being

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!