I have worked with EF for a while now and i have always used LocalDb's for storing data. I want to start working with SQL Server databases instead but I'm having some issues setting up the connection string.
https://msdn.microsoft.com/en-us/library/jj653752(v=vs.110).aspx#sse
https://www.connectionstrings.com/
and looked over google but none of the answers made it work in my case so I must be doing something wrong (some of the connections strings throw an exception others didn't but wouldn't insert anything either into the database neither)
My question is when working with EF & SQL Server, should I use both the connection string in the App.config & setting the path of the DB in the CTOR of the context (by using AppDomain.CurrentDomain.SetData("DataDirectory", path);) or is the app.config sufficient ?
I have tried the following connection strings:
Data Source=.\GURUBEAST-PC\GURUSQL;Initial Catalog=iManager;Trusted_Connection=True;MultipleActiveResultSets=True;
Data Source=.\GURUBEAST-PC\GURUSQL;Database=iManager;Integrated Security=True;Trusted_Connection=True;MultipleActiveResultSets=True;
Data Source=.\GURUBEAST-PC\GURUSQL;AttachDbFilename=C:\Program Files\Microsoft SQL Server\MSSQL11.GURUSQL\MSSQL\DATA\iManager.mdf;Database=iManager;Trusted_Connection=True;MultipleActiveResultSets=True;
Data Source=.\GURUBEAST-PC\GURUSQL;AttachDbFilename=C:\Program Files\Microsoft SQL Server\MSSQL11.GURUSQL\MSSQL\DATA\iManager.mdf;Database=iManager;Trusted_Connection=True;
Data Source=.\GURUBEAST-PC\GURUSQL;Database=iManager;Trusted_Connection=True;
Data Source=.\GURUBEAST-PC\GURUSQL;Initial Catalog=iManager;Integrated Security=SSPI;
Data Source=.\GURUBEAST-PC\GURUSQL;Initial Catalog=iManager;User id=GURUBEAST-PC\GuruBeast;
Where "iManager" is the name of the database. I use Windows auth for my SQL Server instance.
What am I doing wrong ? Should I set my path to the program files folder or the App_Data (I have seen both and tried both but both didn't work)?
Kind regards!
The Data Source key is used to find the machine on which the Sql Server instance runs.
You can have different strings for it but the most common used in a LAN environment is composed using the name of the server machine followed by an eventual instance name.
So, if your local PC is named GURUBEAST-PC and, at install time, you haven't specified any instance name, the connectionstring Data Source contains only the name of the machine GURUBEAST-PC. If you have an instance name then you should add that instance name to you Data Source key. GURUBEAST-PC\GURUSQL
This will guarantee to all the PC in the same LAN the possibility to have the same connectionstring also if the connection is made from the same PC where the SQL Server runs.
If the Data Source points at the local pc, you can use many shortcuts to represent the local PC:
(LOCAL)
localhost
.
\.
and eventually add the instance name to these shortcuts without repeating the PC name
Once you get your host name figured out, Entity Framework will generate your connection string for you. Here's a sample of what your connection string could look like if you were attempting to connect to AdventureWorks database hosted on your local instance of SQL Server 2014 aptly named sql2014.
<connectionStrings>
<add name="AdventureWorksEntities" connectionString="metadata=res://*/DataModels.AdventureWorksDb.csdl|res://*/DataModels.AdventureWorksDb.ssdl|res://*/DataModels.AdventureWorksDb.msl;provider=System.Data.SqlClient;provider connection string="data source=.\sql2014;initial catalog=AdventureWorks;persist security info=True;user id=App_AdventureWorks;password=asdasdfasdfasdf;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
Your db context would then look something like this.Again, EF generates this for you.
public partial class AdventureWorksEntities : DbContext
{
public AdventureWorksEntities()
: base("name=AdventureWorksEntities")
{
}
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
I have a customer database that is kept on a SQL Server on our local network. I would like to create a customer portal that will be on our website that is hosted through another company. How would I connect to that SQL Server database?
Give the website host access rights to the sql server. Assuming Sql Server 2008; go to your management studio and right click the server (root) in the object explorer window and go to properties. You can manage permissions from there. Also, it will show you the "server" to use in your connection string (something like [server]\SQLEXPRESS, which can be used locally and remotely).
Create a proper connection string in the website, preferably in web.config, to use for all of your connections to the database. You can then get this connection string from, say, your data layer via
ConfigurationManager.ConnectionStrings["ConnString_Name"].ConnectionString;
Aside from the correct connection string, you will also need to ensure that the website can communicate with your SQL Server. If you have firewalls, you'll need to configure ports if they are blocked.
The alternative is to create a web service that is hosted on a DMZ zone that will communicate with your sql server internally. The website (hosted by the third party) would communicate via this web service to get the data (you can setup authentication so only those with rights can use this web service). By going this route, you're not exposing your internal sql server directly.
This answer is based on some assumptions because question does not provide all the required information.
For this you need to set ConnectionString property for your connection object.
For example
Data Source=yourIP;Initial Catalog=myDataBase;User ID=myUsername;Password=myPassword;
Here is MSDN link connectionStrings
This is a example of SQLExpress connectionstring in Web.Config
<connectionStrings>
<add
name="LocalSqlServer"
connectionString="data source=.\SQLEXPRESS;Initial Catalog=myDataBase;User ID=myUsername;Password=myPassword;"
providerName="System.Data.SqlClient"
/>
</connectionStrings>
There is a Beginners guide on Code Project which is voted 5, it will give you all you need to get started.
But before you start working with the code, I suggest that you first test the connection with SQL Server management studio. make sure that you can connect and query some data, otherwise you may face some more confusion while trying to pull this off with code only at the first time.
To connect to SQL Server from C#.NET, you need to create a connection string such as below:
private SqlConnection connection; private string connectionString = #"Server=(local);Database=Embedding_SQL_Test;User ID=sa;Password=123"; connection = new SqlConnection( connectionString );
Next, you use the SqlConnection object created above to create a 'SqlCommand', as shown below:
SqlCommand cmd = new SqlCommand( "select * from Customer where CustomerID = #Cid", connection);
The SQL query shown here can be replaced by a SELECT, INSERT, UPDATE queries etc.
Next to execute the SQL queries in the database, you use the following methods: ExecuteReader - to execute SELECT queries ExecuteNonQuery - to execute INSERT, DELETE, UPDATE, and SET statements.
This is a very short description of how to connect to SQL Server database from C# and execute SQL queries in the database. For details about the connection string, the methods and their parameters check the following link: ( http://www.shahriarnk.com/Shahriar-N-K-Research-Embedding-SQL-in-C-Sharp-Java.html ) Here you will also find details about how to pass parameters to the SQL queries as well as calling stored procedures and much more.
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