Using() with insert command in c# doesn't work [duplicate] - c#

I have an ASP.NET application which runs fine on my local development machine.
When I run this application online, it shows the following error:
Format of the initialization string does not conform to specification starting at index 0
Why is this appearing, and how can I fix it?

Check your connection string. If you need help with it check Connection Strings, which has a list of commonly used ones.
Commonly used Connection Strings:
SQL Server 2012
Standard Security
Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;
Trusted Connection
Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;
Connection to a SQL Server instance
The server/instance name syntax used in the server option is the same for all SQL Server connection strings.
Server=myServerName\myInstanceName;Database=myDataBase;User Id=myUsername;
Password=myPassword;
SQL Server 2005
Standard Security
Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;
Trusted Connection
Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;
Connection to a SQL Server instance
The server/instance name syntax used in the server option is the same for all SQL Server connection strings.
Server=myServerName\myInstanceName;Database=myDataBase;User Id=myUsername;Password=myPassword;
MySQL
Standard
Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
Specifying TCP port
Server=myServerAddress;Port=1234;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
Oracle
Using TNS
Data Source=TORCL;User Id=myUsername;Password=myPassword;
Using integrated security
Data Source=TORCL;Integrated Security=SSPI;
Using ODP.NET without tnsnames.ora
Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=MyHost)(PORT=MyPort)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=MyOracleSID)));User Id=myUsername;Password=myPassword;

This might help someone..
My password contained a semicolon so was facing this issue.So added the password in quotes. It was really a silly mistake.
I changed the following :
<add name="db" connectionString="server=local;database=dbanme;user id=dbuser;password=pass;word" providerName="System.Data.SqlClient" />
to
<add name="db" connectionString="server=local;database=dbanme;user id=dbuser;password='pass;word'" providerName="System.Data.SqlClient" />

Set the project containing your DbContext class as the startup project.
I was getting this error while calling enable-migrations.
Even if in the Package Manager Console I selected the right Default project, it was still looking at the web.config file of that startup project, where the connection string wasn't present.

Check your connection string like I forget to add services.AddDbContext<dbsContext>(options => options.UseSqlServer("Default"));
It causes the error and here when I add Configuration.GetConnectionString, then it solves the issue
like now the connection is:
services.AddDbContext<dbsContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Default")));
works fine (This problem is solved for .net core)

Make sure that your connection string is in this format:
server=FOOSERVER;database=BLAH_DB;pooling=false;Connect Timeout=60;Integrated Security=SSPI;
If your string is missing the server tag then the method would return back with this error.

I had the same problem. Locally the site ran fine, but on azure it would fail with the message above.
turns out the problem was setting the connectionstring in the ctor, like this:
public DatabaseContext()
{
Database.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["db"].ConnectionString;
}
Does NOT work, this will:
public DatabaseContext() : base("db")
{
}
Beats me..

Referencing the full sp path resolved this issue for me:
var command = new SqlCommand("DatabaseName.dbo.StoredProcedureName", conn)

I removed &quot at the end of the connection string and it worked
Instead of
App=EntityFramework"
Used
App=EntityFramework;
Set DefaultConnection as below
<add name="DefaultConnection" connectionString="data source=(local);initial catalog=NamSdb;persist security info=True;user id=sa;password=sa;MultipleActiveResultSets=True;App=EntityFramework;" providerName="System.Data.SqlClient" />
Note : In connectionString Do not include :
|x| Metadata info : "metadata=res://*/"
|x| Encoded Quotes : """

I solved this by changing the connection string on the publish settings of my ASP.NET Web Api.
Check my answer on this post: How to fix error ::Format of the initialization string does not conform to specification starting at index 0::

I had the same error. In my case, this was because I was missing an closing quote for the password in the connection string.
Changed from this
<add name="db" connectionString="server=local;database=dbanme;user id=dbuser;password='password" providerName="System.Data.SqlClient" />
To
<add name="db" connectionString="server=local;database=dbanme;user id=dbuser;password='password'" providerName="System.Data.SqlClient" />

In my case, I got a similar error:
An unhandled exception was thrown by the application. System.ArgumentException: Format of the initialization string does not conform to specification starting at index 91.
I change my connection string from:
Server=.;Database=dbname;User Id=myuserid;Password=mypassword"
to:
Server=.;Database=dbname;User Id=myuserid;Password='mypassword'"
and it works, I added single quotes to the password.

In my case the problem was in the encoding of the connection string.
In local it worked without problems, but when installing it in a production environment it showed this error.
My application allows to set the connection string using a form and when the connection string was copied from local to production, invisible characters were introduced and although the connection string was visually identical at the byte level it was not.
You can check if this is your problem by following these steps:
Copy your connection string to Notepad++.
Change the codification to ANSI. In Menu Encoding>Encode to ANSI.
Check if additional characters are included.
If these characters have been included, delete them and paste the connection string again.

Got this problem with SQLite in aspnetcore. I wrote
"DefaultSQLiteConnection": "MyBlog.db"
instead of
"DefaultSQLiteConnection": "Data Source = MyBlog.db"

My generated password contained few characters that were valid in AWS RDS, but for some reason my .NET app could not handle it. The solutions that worked for me, was to generate new password without characters like ` (backtick).

In my case, it was...
index: 58
but what ended up happening was the password generated had a single quote in it. SQL Server accepted that, but my connection string had trouble parsing it. Hope this saves someone at least a few minutes, because it cost me an hour to two before I relized what was going on. cheers

Hope this helps someone in the future. My connection string had blank values wrapped in double quotes, e.g. User ID="". So to resolve it I had to escape the double quotes.
Dim ConString = "Data Source=MYSERVER;User ID="";Initial Catalog=Northwinds..."
ConString = ConString.Replace("""", """""")

This also happens when you copy a web page from one solution to another, then you run your solution and find out that it has a different connection string name in the webconfig. Then you carelessly change the name of the connection string in the properties panel in the design view of the page.
Better to just change it in the code portion instead of the design.

My problem was I added database logging code to my constructor for a DB object, and this seemed to cause havoc on my azure deployment profile.
FYI - I simplified this example, in the real code this was turned off in production (but still in the code)
public class MyDB : DbContext
{
public MyDB()
{
this.Database.Log = x => { Debug.WriteLine(x); };
}
}

I had typo in my connection strings "Database==PESitecore1_master"
<add name="master" connectionString="user id=sa;password=xxxxx;Data Source=APR9038KBD\SQL2014;Database==PESitecore1_master"/>

I had the same problem and finally I managed to resolve it in the following way:
The problem was in the connection string definition in my web.config.
<add name="DefaultConnection" connectionString="DefaultConnection_ConnectionString" providerName="System.Data.SqlClient"/>
The above worked perfect locally because I used a local Database when I managed users and roles. When I transfered my application to IIS the local DB was not longer accessible, in addition I would like to use my DB in SQL Server. So I change the above connection string the following SQL Server DB equivalent:
<add name="DefaultConnection" connectionString="data source=MY_SQL_SERVER; Initial Catalog=MY_DATABASE_NAME; Persist Security Info=true; User Id=sa;Password=Mybl00dyPa$$" providerName="System.Data.SqlClient"/>
NOTE: The above, also, suppose that you are going to use the same SQL Server from your local box (in case that you incorporate it into your local web.config - that is what exactly I did in my case).

I had the same issue, came to find out that the deployment to IIS did not set the connection strings correctly. they were '$(ReplacableToken_devConnection-Web.config Connection String_0)' when viewing the connection strings of the site in IIS, instead of the actual connection string. I updated them there, and all worked as expected

I copied and pasted my connection string configuration into my test project and started running into this error. The connection string worked fine in my WebAPI project. Here is my fix.
var connection = ConfigurationManager.ConnectionStrings["MyConnectionString"];
var unitOfWork = new UnitOfWork(new SqlConnection(connection.ConnectionString));

My problem wasn't that the connection string I was providing was wrong, or that the connection string in the app.config I thought I was using was wrong, but that I was using the wrong app.config.

For the one other unfortunate soul that is managing a legacy webforms application that uses an inline sqldatasource, along with connection strings stored in web.config, then you may get this error if you access your connection string like <%APSDataConnectionString%> instead of
<%$ ConnectionStrings:MyConnectionString %>. This happened to us when upgrading .NET from 3.5 to 4.x.
<asp:DropDownList ID="ddl" runat="server" DataSourceID="SqlDataSource1"
DataTextField="value" DataValueField="id"></asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:MyConnectionString %>"
SelectCommand="select id, value from a_table">
</asp:SqlDataSource>

In my case the problem was that on the server, a different appsettings.json file was used by the application.

I had this error too and was able to solve it as follows:
I previously wrote the connectionstring to the appsettings.json into a section that I created (ConnectionsStrings (notice the extra "s") and tried to connect to my database which caused the error. It was an ASP.NET CORE application and so I wanted to connect to it with the .GetConnectionString Method (details on that here). It seems that this method implicitly searches for a connectionstring in the "ConnectionStrings"-section, which didn't exist. When I changed/corrected it to "ConnectionStrings" it worked as expected.

I had the same problem spent an entire day. The error indicates Connection string issue for sure as index 0 is connection string. My issue was in the Startup class. I used:
var connection = Configuration["ConnectionStrings:DefaultConnection"];
services.AddControllersWithViews();
services.AddApplicationInsightsTelemetry();
services.AddDbContextPool<Models.PicTickContext>(options => options.UseSqlServer("connection"));`
which is wrong instead use this:
services.AddControllersWithViews();
services.AddApplicationInsightsTelemetry();
services.AddDbContextPool<Models.PicTickContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
and my problem was solved.

I had this error and it turned out that the cause was that I had surrounded a (new) tableadapter with a Using/End Using. Just changing the tableadapter to stay live for longer (duration of class in my instance) fixed this for me. Maybe this will help someone.

Sometimes the Sql Server service has not been started. This may generate the error. Go to Services and start Sql Server. This should make it work.

As I Know, whenever you have more than 1 connection string in your solution(your current project, startup project,...), you may confront with this error
this link may help you
click

Related

"Keyword not Supported" Error message while fetching connection string from azure application setting using environment variable

I am trying to get the connection string from Azure Application settings using environment variables, But it seems that the format of the connection string that I am putting in Azure App setting is not proper.Here is my original connection string that works fine in localhost.
<add connectionString="Server=tcp:****.database.windows.net,1433;Initial Catalog=***;
Persist Security Info=False;User ID=******;Password=*********;MultipleActiveResultSets=False;
Encrypt=True;TrustServerCertificate=False;Connection Timeout=1200000;
Max Pool Size=500;Pooling=true;" name="Con_String"></add>
I am putting "Server=tcp:****.database.windows.net,1433;Initial Catalog=****;Persist Security Info=False;User ID=****;Password=****;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=1200000;Max Pool Size=500;Pooling=true;"as the con_string value in Azure Application Setting
Now for fetching the Connection string at runtime I am using Environment variable as string ConnectionString = Environment.GetEnvironmentVariable("SQLAZURECONNSTR_Con_String");
But during running the web app I am getting the exception message Keyword not supported: '"Server'.
I tried the approaches in
Retrieve and use Windows Azure's connection strings? and other similar posts ,but didn't work. Am I missing something silly here?
Am I missing something silly here?
If you still get the Keyword not supported: '"Server' or The ConnectionString property has not been initialized.
I assume that you don't save the appsetting after you add the connection string the WebApp appseting.
The following code are both working on my side.
ConnectionString = ConfigurationManager.ConnectionStrings["Con_String"].Connec‌​tionString.
ConnectionString = Environment.GetEnvironmentVariable("SQLAZURECONNSTR_Con_Stri‌​ng")
Test Result:
Note: as GauravMantri mentioned that there is no need quotes (") in the connection string in the Azure WebApp appsetting.
In my case issue was connected with the stupid mistake: when copy/pasted connection string to Notepad++ I somehow missed that newline operator appeared because of the Notepad++ was wrapping the text or smth else.
In any case, I've copy/pasted to Notepad then replaced User ID and Password, then copy/pasted again to the server, Saved the settings then Restarted the server.
Finally, issue fixed.

Error to connect SQL Database at hosting website

did anybody host asp.net website with sql database?
I couldn't integrate my database connection with .mdf sql file (in my App_Data folder).
Is there anything need to change my data connection string (connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\example.mdf;Integrated Security=True;").
My host website: www.hostgator.com
It's really helpful if u give me proper suggestions step by step.
Database name is missing your Connection String :
Change as below:
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\example.mdf;Initial Catalog=mydatabase;Integrated Security=True;"
your connection string (connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\example.mdf;Integrated Security=True;") is the one you use when running locally. change it to the connection string that your hosting site gave you. it is usually on the database information.
After initial setup has been done, test your connecting weather it is successful or not then
write your connecting string as below:
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\example.mdf;Initial Catalog=yourDBname;Integrated Security=True;"
Where yourDBname is the name of your database that you have already given.
Hope this helps
Regards,
Rubel

WCF : remote SQL Server 2005 database connection

I'd like to know how to link my WCF application with a remote SQL Server database. By remote, I mean that is on the same network than me but not on the same computer/project.
I've the controll of the computer where the database is stored on.
What I've done so far : create my WCF application and try to add an ADO.NET connection. My issue : where to find the name of the server ? (and also : is it the good way to proceed ?).
Thanks !
where to find the name of the server?
Three options:
whoever "owns" the database server tells you the details, and you put them in a configuration file (or some other configuration system)
whoever "owns" the database server tells some key user the details, and the user puts them into a screen / api in the application
something like the above, but you try to discover sql servers at runtime via SqlDataSourceEnumerator (not a fan of this option, to be honest)
Conntion string should look like
Server=myServerName\myInstanceName;Database=myDataBase;User Id=myUsername;Password=myPassword;
In Place of myServerName you can use IPAdress of machine
I suggest you add connectionString in the Web.config file of the application
<add name="connectionString"
connectionString="Data Source=ServerName/PC-Name;Initial Catalog=DatabaseName;User ID=userid;Password=pass"
providerName="System.Data.SqlClient" />
Use the connection string in your code/Logic
string conn = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;

WCF & Entity Framework & SQL Server - "The underlying provider failed on Open"

I am successfully running tests through the the WCF Test Client, until I try to pull in data with Entity Framework.
To make sure I'm not doing anything stupid, I downloaded the sample code from this tutorial, which is doing something similar: http://www.codeproject.com/KB/WCF/WCFandEF.aspx
...and when I run it, I get the same error in a similar place:
var productEntity = (from p in context.ProductEntities
where p.ProductID == id
select p).FirstOrDefault();
The error is
The underlying provider failed on Open.
I can open the database fine from a "normal application" with the same connection string, it seems to be specific accessing the DB from the WCF test client.
Research here and on Google for "The underlying provider failed on Open." usual indicates that it's a connection string problem, but I'm pretty sure it's not in this case.
So now I expect it's some sort of permissions problem.
I am using SQL Server and Windows 7, with visual studio 2010.
I have been banging my head since yesterday, so any help or protective head gear appreciated.
Edited to include connection string
<add name="NorthwindEntities"
connectionString="metadata=res://*/Northwind.csdl|res://*/Northwind.ssdl|res://*/Northwind.msl;provider=System.Data.SqlClient;provider
connection string="Data Source=localhost;Initial Catalog=Northwind;User ID=sa;MultipleActiveResultSets=True""
providerName="System.Data.EntityClient" />
This error means 100% a problem in your connection string.
A good way to create a surely working connection string is to create a new(dummy) project, add an Entity Framework Data Model to it, select "Generate Model from Database", select your required connection, and click "Test Conntection" to be sure it works.
Make sure ""Save entity conection settings in App.Config as:..." is ticked.
Than, in you web/app.Config, you have a Connection String you can copy+paste to your own project
Have you tried inserting the database password into the connection string?
It worked for me.
Reference:
http://stack247.wordpress.com/2011/03/02/entity-framework-exception-the-underlying-provider-failed-on-open/
Well I had the same error for days... actualy for two days and Yes I found the solution Alhamdulillah..
As for me... I had Windows Authentication set on my Entity Service Connection.. So What I did was I went to IIS 7 Application Pool Advanced Settings for the web service... Changed the Identity from 'ApplicationPoolIdentity' to 'Network Service' and I setup my current user name and password as well.
I might face some other issues later on, still I would say a Good Start :-)!
I was remove "integrated security=True;" solved this way.

MSSQL Error 'The underlying provider failed on Open'

I was using an .mdf for connecting to a database and entityClient. Now I want to change the connection string so that there will be no .mdf file.
Is the following connectionString correct?
<connectionStrings>
<!--<add name="conString" connectionString="metadata=res://*/conString.csdl|res://*/conString.ssdl|res://*/conString.msl;provider=System.Data.SqlClient;provider connection string="Data Source=.\SQL2008;AttachDbFilename=|DataDirectory|\NData.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />-->
<add name="conString" connectionString="metadata=res://*/conString.csdl|res://*/conString.ssdl|res://*/conString.msl;provider=System.Data.SqlClient;provider connection string="Data Source=.\SQL2008;Initial Catalog=NData;Integrated Security=True;Connect Timeout=30;User Instance=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
Because I always get the error:
The underlying provider failed on Open
I had this error and found a few solutions:
Looking at your connection string, it looks valid. I found this blog post, the problem here is that they were using Integrated Security. If you are running on IIS, your IIS user needs access to the database.
If you are using Entity Framework with Transactions, Entity Framework automatically opens and closes a connection with each database call. So when using transactions, you are attempting to spread a transaction out over multiple connections. This elevates to MSDTC.
(See this reference for more information.)
Changing my code to the following fixed it:
using (DatabaseEntities context = new DatabaseEntities())
{
context.Connection.Open();
// the rest
}
context.Connection.Open() didn't help solving my problem so I tried enabling "Allow Remote Clients" in DTC config, no more error.
In windows 7 you can open the DTC config by running dcomcnfg, Component Services -> Computers -> My Computer -> Distributed Transaction Coordinator -> Right click to Local DTC -> Security.
You should see innerException to see what the inner cause of throwing of
error is.
In my case, the original error was:
Unable to open the physical file "D:\Projects2\xCU\xCU\App_Data\xCUData_log.ldf". Operating system error 5: "5(Access is denied.)".
An attempt to attach an auto-named database for file D:\Projects2\xCU\xCU\App_Data\xCUData.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
which solved by giving full permission to current user for accessing related mdf and ldf files using files' properties.
I found the problem was that I had the server path within the connection string in one of these variants:
SERVER\SQLEXPRESS
SERVER
When really I should have:
.\SQLEXPRESS
For some reason I got the error whenever it had difficulty locating the instance of SQL.
This is common issue only. Even I have faced this issue. On the development machine, configured with Windows authentication, it is worked perfectly:
<add name="ShoppingCartAdminEntities" connectionString="metadata=res://*/ShoppingCartAPIModel.csdl|res://*/ShoppingCartAPIModel.ssdl|res://*/ShoppingCartAPIModel.msl;provider=System.Data.SqlClient;provider connection string="data source=.\SQlExpress;initial catalog=ShoppingCartAdmin;Integrated Security=True;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />
Once hosted in IIS with the same configuration, I got this error:
The underlying provider failed on Open
It was solved changing connectionString in the configuration file:
<add name="MyEntities" connectionString="metadata=res://*/ShoppingCartAPIModel.csdl|res://*/ShoppingCartAPIModel.ssdl|res://*/ShoppingCartAPIModel.msl;provider=System.Data.SqlClient;provider connection string="data source=MACHINE_Name\SQlExpress;initial catalog=ShoppingCartAdmin;persist security info=True;user id=sa;password=notmyrealpassword;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />
Other common mistakes could be:
Database service could be stopped
Data Source attributes pointing to a local database with Windows authentication and hosted in IIS
Username and password could be wrong.
When you receive this exception, make sure to expand the detail and look at the inner exception details as it will provide details on why the login failed. In my case the connection string contained a user that did not have access to my database.
Regardless of whether you use Integrated Security (the context of the logged in Windows User) or an individual SQL account, make sure that the user has proper access under 'Security' for the database you are trying to access to prevent this issue.
The SQL Server Express service were not set tostart automatically.
1) Go to control panel
2) Administrative Tools
3) Service
4) Set SQL Server express to start automatically by clicking on it
5) Right click and start the service
I hope that will help.
I had a similar issue with the SQL Server Express Edition on Windows Server 2003. I simply added the network service as a user in the database security.
This can also happen if you restore a database and the user already exists with different schema, leaving you unable to assign the correct permissions.
To correct this run:
USE your_database
EXEC sp_change_users_login 'Auto_Fix', 'user', NULL, 'cf'
GO
EXEC sp_change_users_login 'update_one', 'user', 'user'
GO
I posted a similar issue here, working with a SQL 2012 db hosted on Amazon RDS. The problem was in the connection string - I had "Application Name" and "App" properties in there. Once I removed those, it worked.
Entity Framework 5 and Amazon RDS - "The underlying provider failed on Open."
Make sure that each element value in the connection string being supplied is correct. In my case, I was getting the same error because the name of the catalog (database name) specified in the connection string was incorrect.
I had a similar issue with exceptions due to the connection state, then I realized I had my domain service class variable marked as static (by mistake).
My guess is that once the service library is loaded into memory, each new call ends up using the same static variable value (domain service instance), causing conflicts via the connection state.
I think also that each client call resulted in a new thread, so multiple threads accessing the same domain service instance equated to a train wreck.
I had the same problem but what worked for me was removing this from the Connection String:
persist security info=True
I had a similar error with the inner exception as below:
operation is not valid for the state of the transaction
I could resolve it by enabling DTC security settings.
Go To Properties of DTC, under Security Tab, check the below
Network DTC Access
Allow RemoteClients
Transaction Manager Communication
Allow Inbound
Allow Outbound
If you happen to get this error on an ASP.NET web application, in addition to other things mentioned check the following:
Database User Security Permissions (which users are allowed access to your database.
Check your application pool in IIS and make sure it's the correct one that is allowed access to your database.
I got rid of this by resetting IIS, but still using Integrated Authentication in the connection string.
Defining a new Windows Firewall rule for SQL Server (and for port 1433) on the server machine solves this error (if your servername, user login name or password is not wrong in your connection string...).
NONE of the answers worked for me
I think that some of us all make silly mistakes, there are 100 ways to fail ...
My issue was new project, I setup all the configuration in another project, but the caller was a Web Api project in which I had to copy the same connection string in the Web api project.
I think this is crazy considering I was not even newing up dbcontext or anything from the web api.
Otherwise the class library was trying to look for a Database named
TokenApi.Core.CalContext
of which my project is named TokenApi.Core and the CalContext is the name of the connection string and the file name
I was searching all over the web for this problem. I had the wrong name in the connection string, please check you connection string in web.config. I had name="AppTest" but it should have been name="App".
In my AppTestContext.cs file I had:
public AppTestContext() : this("App") { }
Wrong connection string:
<add connectionString="Data Source=127.0.0.1;Initial Catalog=AppTest;Integrated Security=SSPI;MultipleActiveResultSets=True" name="AppTest" providerName="System.Data.SqlClient" />
Right connection string:
<add connectionString="Data Source=127.0.0.1;Initial Catalog=AppTest;Integrated Security=SSPI;MultipleActiveResultSets=True" name="App" providerName="System.Data.SqlClient" />
A common mistake that I did because I was moving application from once pc to another and none of the above worked was that I forgot to copy the connection string to both App.Config and Web.Config!
I had a similar problem: In my test-cases executions I always got this error. I found out, that my "Distributed Transaction Service" was not started (run: services.msc -> start "Distributed Transaction Service" (best to set it to start automatic)). After I did that, it worked like a charm...
I was also facing the same issue. Now I have done it by removing the user name and password from the connection string.
For me it was just a simple mistake:
I used Amazon EC2, and I used my elastic IP address in the connection string, but when I changed IP addresses I forgot to update my connection string.
I had this error suddenly happen out of the blue on one of our sites. In my case, it turned out that the SQL user's password had expired! Unticking the password expiration box in SQL Server Management Studio did the trick!
I had the same issue few days ago, using "Integrated Security=True;" in the connection string you need to run the application pool identity under "localsystem" Sure this is not recommended but for testing it does the job.
This is how you can change the identity in IIS 7:
http://www.iis.net/learn/manage/configuring-security/application-pool-identities
In IIS set the App Pool Identity As Service Account user or Administrator Account or ant account which has permission to do the operation on that DataBase.
In my case I had a mismatch between the connection string name I was registering in the context's constructor vs the name in my web.config. Simple mistake caused by copy and paste :D
public DataContext()
: base(nameOrConnectionString: "ConnStringName")
{
Database.SetInitializer<DataContext>(null);
}
I had this problem because the Application Pool login this app was running under had changed.
In IIS:
Find the Application pool by clicking on your site and going to Basic Settings.
Go to Application Pools.
Click on your site's application pool.
Click on Advanced Settings.
In Identity, enter account login and password.
Restart your site and try again.
I have solved this way.
Step 1:
Open Internet Information Service Manager
Step 2:
Click on Application Pools in left navigation tree.
Step 3:
Select your version Pool. In my case, I am using ASP .Net v4.0. If you dont have this version, select DefaultAppPool.
Step 4:
Right click on step 3, and select advanced settings.
Step 5:
Select Identity in properties window and click the button to change the value.
Step 6:
Select Local System in Built-in accounts combo box and click ok.
That's it. Now run your application. Everything works well.
Codeproject Solution : the-underlying-provider-failed-on-open
I get this error when call async EF method from sync Main console (await was skipped).
Because async opening a connection was for an already disposed data context.
Solve: call async EF methods correctly

Categories

Resources