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")
{
}
Related
I'm using DbUp to migrate my SQL Server database. I've implemented this in a console application, that accepts the connection string. If I run this against my local SQL Server database, it works. If I run it against an Azure SQL database, it works as well.
However, if I run it against a LocalDb database that was created on the fly in my tests, I get an exception.
The line on which the exception occurs is:
EnsureDatabase.For.SqlDatabase(connectionString);
and the connection string parameters contains:
Data Source=(LocalDB)\MSSQLLocalDB;AttachDBFileName=C:\Projects\Prim\mgp\Prim.Mgp.Infrastructure.DataAccessTests\bin\Debug\netcoreapp2.2\Data\ccf243baa63eb4ea258b0155.mdf;Initial Catalog=ccf243baa63eb4ea258b0155;Integrated Security=True;MultipleActiveResultSets=True;
The exception is:
System.Data.SqlClient.SqlException: 'Database 'C:\Users\ludwigs\AppData\Local\Microsoft\Microsoft SQL Server Local DB\Instances\MSSQLLocalDB\master.mdf' already exists. Choose a different database name. Cannot attach the file 'C:\Projects\Prim\mgp\Prim.Mgp.Infrastructure.DataAccessTests\bin\Debug\netcoreapp2.2\Data\ccf243baa63eb4ea258b0155.mdf' as database 'master'.'
...which is a bit strange, because it mentioning a different database than I specified in the connection string.
Does anyone have a clue what I might be doing wrong?
PS: if I remove the troublesome line of code , I can query my database without problems.
There is a problem with the AttachDBFileName in the connection string, try to test with this connection string.
And DBUp run the master so it can create the database using Ensure Database.For.Sql Database,
<connectionStrings>
<add name="Database" connectionString="Server=.;Database=Migrations_DbUp;Integrated Security=true"/>
</connectionStrings>
I have created an application using Entity Framework 6 code-first, in ASP.NET MVC 5, and am bin deploying it to my server. Everything works fine, except for the operations/controller actions that involve database usage.
I am uploading the once-generated database file from my computer to the App_Data folder of the server.
Upon deploying, I changed the connection string in my web.config file from:
connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-NERC_Main-20160104065223.mdf;Initial Catalog=aspnet-NERC_Main-20160104065223;Integrated Security=True"
to
connectionString="Data Source=.;AttachDbFilename=|DataDirectory|\aspnet-NERC_Main-20160104065223.mdf;Initial Catalog=aspnet-NERC_Main-20160104065223;Database=aspnet-NERC_Main-20160104065223.mdf;Trusted_Connection=Yes;Integrated Security=True;"
which throws an error of
CREATE DATABASE permission denied in database 'master'.
A probable cause of this is because the present database file is not being attached, and the entity framework is trying to generate a new database in some other, restricted directory.
I read that the AttachDbFileName is valid for SQL Server Express instances only, which in my case doesn't exist.
How can I modify the connection string so that my current, already uploaded database is utilized.
Note:
The remote server has a full installation of SQL Server 2008 R2. The server does not support user instances. My database is not password protected, and hence I've set the Integrated Security property value to True. I'll provide any other information if required.
If you have a full version of SQL Server, you cannot just use AttachDbFileName. Instead, you need to copy the .mdf (and .ldf) to the SQL Server data file location and then you need to attach the database in SQL Server Management Studio to the server instance.
From that point on, you can reference that database in your connection string using the server name, and the logical database name - something like this:
Server=.;Database=aspnet-NERC_Main-20160104065223;Integrated Security=True;
Depending on your database setup, you may or may not be able to use the Integrated Security - maybe you'll need to have a specific SQL Server login and specify that login (and its password) in your connection string instead:
Server=.;Database=aspnet-NERC_Main-20160104065223;User ID=YourUserName;Password=YourPassword
See this site here for a ton of sample of how to build valid connection strings for SQL Server.
In one of my ASP.NET MVC projects, the connectionString is given as follows in the web.config file.
<connectionStrings>
<add name="db_connection"
connectionString="Data Source=ASTRONOMY
Initial Catalog=GALLERIA;
user=sa_galleria;
password=Tyrr#!!55u;
providerName="" />
</connectionStrings>
This connection string is supposed to work on Microsoft SQL Server (Full Editions).
I found that this connection setting is a little different than what the MSDN article here explains. Especially, the following differences exist:
Is the connectionStrings configuration case-insensitive?
What does ASTRONOMY refer to here? (as Data Source)
Can User Id be shortened as user?
What value is set for providerName if it's omitted or has an empty value?
Thank you for your clarification.
1.Is the connectionStrings configuration case-insensitive?
Some parts are, such as password
2.What does ASTRONOMY refer to here? (as Data Source)
That's the servername and instance eg SERVER\SQLEXPRESS
3.Can User Id be shortened as user?
Nope ok, yes UID see comments
4.What value is set for providerName if it's omitted or has an empty value?
NET Framework Data Provider see SQL providerName in web.config
Have a look at
https://connectionstrings.com/sql-server/
Data Source=ASTRONOMY
Data Source -or- Server -or- Address -or- Addr -or- Network Address
The name or network address of the instance of SQL Server to which to connect. The port number can be specified after the server name: server=tcp:servername, portnumber. When specifying a local instance, always use (local). To force a protocol, add one of the following prefixes: np:(local), tcp:(local), lpc:(local)
ADO.NET 2.0 does not support asynchronous commands over shared memory for SQL Server 2000 or earlier. However, you can force the use of TCP instead of shared memory, either by prefixing tcp: to the server name in the connection string, or by using localhost.
Initial Catalog=GALLERIA;
Initial Catalog -or- Database
The name of the database.
user=sa_galleria;
The SQL Server login account.
password=Tyrr#!!55u;
Password -or- Pwd
The password for the SQL Server account logging on. Not used with (the strongly recommended) 'Integrated Security=true' option. Case sensitive
providerName=""
System.Data.SqlClient is the .NET Framework Data Provider for SQL Server. ie .NET library for SQL Server.
In the web.config you should have the System.Data.SqlClient as the value of the providerName attribute. It is the .NET Framework Data Provider you are using.
Source: https://www.connectionstrings.com/all-sql-server-connection-string-keywords/
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;
Currently I am using SQL Server CE for persisting my data for which I am providing with a .sdf and connection string mentioned in app.config pointing to this .sdf file.
Now I want to provide user with the flexibility to have the data stored in their own SQL Server database if present at there disposal.
Now I am facing the problem of how to change the connection string at runtime if user chooses to uses its own database ?
Or if restrict them to use my predefined .mdf file how to attach that in their SQL Server ?
My recommendation would be to have 2 connection strings in the configuration file (app or web). There is a special section for them intuitively called ConnectionStrings. You can then switch between them based on other settings.
Changing connection strings dynamically is actually pretty easy to do as long as you have a place to store the new settings (ie. web or app config files). If you provide a way for them to enter the server information you can use the ConfigurationManager class to update your app/web.config.
Ado.net typically has parameters on almost any db connection object that allows you to specify the connection string as an arguement. Additionally, there are helper classes that can be used to construct the connection string on the fly like the SqlConnectionStringBuilder or EntityConnectionStringBuilder. I personally love the Entity Framework as it allows you to create the database from the model itself if it does not already exist, provided you already have the connection string.