Ok, so I'm doing a website in .Net and for one of my validators, I'm trying to connect to my database. It's a database that I created in my App_Data folder, so it's a local one. The thing is, I have the following on my C# file:
SqlConnection db = new SqlConnection();
db.ConnectionString = "Data Source=(LocalDB)\v11.0;AttachDbFileName=|DataDirectory|\baseDados.mdf;Integrated Security=True";
db.Open();
//MORE CODE
I've got an error on my ConnectionString. Can't I use the same connectionstring that the one in my web.config file? I have been looking to how to connect to my database, but none of the solutions worked for me 'till now. I'm probably overlooking something. Thanks. :)
|DataDirectory| is a pointer in the config that gets replaced by the actual location of the database. You are using an attached database, so it is looking for the actual directory the data file is located in.
My suggestion, as it is more likely to be like production, is attach the database file to the database server. Since it is .mdf, I am guessing SQL Server (99.9% sure it is SQL Server). You will then alter your database connection string to point to the server, database name, etc. The main change will be the center section. The other option is find the actual location of the file and attempt from there. This should work, as that is what the server does for you when it pulls from config.
I don't have time to look, but I bet there is something in config that points where that file is, or it is automatically stored in a specific location by the framework. A quick Google search should yield answers.
Related
I'm doing my homework, a WCF service that uses SQL Server with Entity Framework, hosted through a console application, and using a WPF client.
There are 3 different projects, and the host and the service is in the same solution. I've included the Entity Framework connection string in the console hosts' app.config file from the web.config file from the service. This way the server and the host throw an exception when I try to make a query:
System.Data.Entity.Core.EntityException: 'The underlying provider failed on Open.'
The inner exception says:
SqlException: An attempt to attach an auto-named database for file C:\Users\username\source\repos\BlogAppWcf\BlogHost\bin\Debug\BlogDb.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
So it basically searches for the .mdf file in it's own project folder, while it's inside the service's App_Data folder.
The original connection string looks like this, I copied this to the host's app.config from the web.config:
connectionString="metadata=res://*/BlogDbEntities.csdl|res://*/BlogDbEntities.ssdl|res://*/BlogDbEntities.msl;
provider=System.Data.SqlClient;
provider connection string="
data source=(LocalDB)\MSSQLLocalDB;
attachdbfilename=|DataDirectory|\BlogDb.mdf;
integrated security=True;
MultipleActiveResultSets=True;App=EntityFramework""
I've tried modifying the AttachDbFilename attribute in the app.config, I gave it an absolute path like this:
attachdbfilename=C:\Users\username\source\repos\BlogAppWcf\BlogAppWcf\App_Data\BlogDb.mdf;
and this way it works like a charm! No more exceptions on queries.
But this isn't the right way to do it, especially because I have to send it to my teacher. I want to give it a relative path, just like this:
attachdbfilename=..\..\..\BlogAppWcf\App_Data\BlogDb.mdf;
but it doesn't work this way.
Has anyone got any suggestions, maybe I'm doing or thinking something completely wrong?
According to your description and the issue you encountered, I think the problem boils down to the fact that the attached database is not properly attached to VS built-in database server instance. For this reason, I think we could configure the EntityFramework with VS built-in database instance string.
Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=MyStore;Integrated
Security=True;Connect
Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False
And then override the seed method of the DropCreateDatabaseAlways/DropCreateDatabaseIfModelChanges class to provide the seed data.
Feel free to let me know if there is anything I can help with.
I just created a desktop Winforms application with localhost database.
The connect string I am using is this:
SqlConnection connect = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Administrator\Desktop\learningsystem\LearningSystem\LearningSystem\LearningSystem.mdf;Integrated Security=True");
If I want to run my application on other computers, how should I make it work?
EDIT:SOLUTION
Thank for all the help! I tried the following steps. I think it is working now. But please correct me if I did something tricky.
1. add a new setting item in project property setting. App.config will automatically update:
<connectionStrings>
<add name="LearningSystem.Properties.Settings.LearningConn" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\LearningSystem.mdf;Integrated Security=True;Connect Timeout=30"
providerName="System.Data.SqlClient" />
</connectionStrings>
2. In my program, just add the following statement to connect to the sql server
SqlConnection connect = new SqlConnection(#"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename=|DataDirectory|\LearningSystem.mdf;Integrated Security = True; Connect Timeout = 30");
Further question
If others will run this application on their computer(not in the same network), they just go into the project setting and change the value by selecting the database file I provide to them,the connectionString will automatically change, right?
Thanks!
It's generally a bad idea to hard code such stuff in your application. Normally, application settings and connection strings are placed in the application's configuration file (in the ConnectionStrings section).
Just like with all strings, you could build your connectionstring from dynamic parts (variables, settings, etc.) and then pass that generated connectionstring to the SqlConnection constructor. Again, to make those separate parts configurable without hard coding them in your application, you might want to add them to your application's configuration file (in the AppSettings section). But IMHO this is an overly complex solution in most scenarios. Putting the entire connectionstring in the ConnectionStrings section is more straightforward (and more flexible).
Anyway, again, to make your application configurable, you might use your application's configuration file (App.config or Web.config), you need to add a reference to System.Configuration in your project's .NET Framework dependencies and use the AppSettings and ConnectionStrings properties of the System.Configuration.ConfigurationManager class.
(Of course, there are more ways to make your application configurable. But using the application configuration file is one of the most straightforward solutions.)
Edit:
When deploying your app to another computer, you need to copy its database over too. If you want to use the application on multiple machines and let them connect to the same database, you might want to leave LocalDB and migrate the data to a SQL Server (Express) instance and make it accessible over the (local) network.
Edit 2 (regarding the recent edits in your post):
I see in step 1 that you are using an application setting (called LearningConn) in your solution now. That's fine. However, it is important that you also use that setting in step 2, like this:
SqlConnection connect = new SqlConnection(Properties.Settings.Default.LearningConn);
If you change the setting in Visual Studio, it will update the connection string. Since the setting will probably have application scope, it will not be possible to update the setting/connection string within your application in runtime (by the user).
I'm not sure if your connection string using |DataDirectory| will always work as expected in all scenarios. I have only been using it in ASP.NET webapplications. If it does work in WinForms applications, you might read this document to learn how to set it up. But personally I am somewhat sceptical about this approach.
I personally would opt for a solution where you use a placeholder in your connection string, which you replace with the full path to the .mdf file before you pass it to your SqlConnection constructor.
When you use "{DBFILE}" as the placeholder, for example, the value of your LearningConn setting would look like this:
Data
Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename={DBFILE};Integrated
Security=True;Connect Timeout=30
(Note that this value should be a single line without any line breaks!)
You might create a separate setting in your application called DbFile (of type string) to store the actual value that should be put in place of {DBFILE} in your connection string. When you use scope "user" for that setting, the value might be changed from within the application by the user. When saved, it might not be saved directly in the application's configuration file, however, but in an additional configuration file hidden somewhere in the user's Windows user profile. You might read this document to learn more about application settings.
Your code in step 2 might eventually look something like this:
string connectString = Properties.Settings.Default.LearningConn;
string dbFile = Properties.Settings.Default.LearningSystemDb;
connectString = connectString.Replace("{DBFILE}", dbFile);
SqlConnection connect = new SqlConnection(connectString);
To let your application's users select and store the database .mdf file to use, you might include (a variation of) the following code in your application somewhere:
using (var dlg = new System.Windows.Forms.OpenFileDialog())
{
dlg.Title = "Select database file to use";
dlg.Filter = "Database Files (*.mdf)|*.mdf";
dlg.CheckFileExists = true;
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Properties.Settings.Default.DbFile = dlg.FileName;
Properties.Settings.Default.Save();
}
}
Your question is not clear!
you need work with one Database on 2 or more PC?!
OR
you need work with 2 separate programs?
if you need 2 separate programs :
you must copy .mdf file to other PC at same address or keep mdf address in app.config and read it before connect to SQL.
How to Read From app.config
if you need work with one Db you must connect to dataBase Server such as SQL Server and keep connection string in app.config in connectionStrings tag.
Get connection string from App.config
If you want to work on other PCs, rather than building it dynamically make the connection string more generic:
Server=(localdb)\\mssqllocaldb;Database=LearningSystem;Trusted_Connection=True;MultipleActiveResultSets=true
This should create the mdf file under 'mssqllocaldb' in %appdata% for each user. You might need LocalDb installed (which you tick during SQL Server installation)
After a few years, I have returned to writing in C# and I am really struggling here - I would like to have my app to have a local SQL database. I have added Service-based database and "Database1.mdf" was added to my project. I created a table and added some data just to see if it is working but I cannot connect to it. I tried numerous connection strings with no success (Server not accessible).
Do I need to run something else in the background? I thought that I might have a local database and with .NET client I can access it, and I hoped it would work whenever I bring my application (also not requiring any SQL server running). Is that wrong?
If you don't require any SQL server, take a look at SQLite. This is lite SQL database engine. Database is just one file. C# has a great library to SQLite on NuGet: https://www.nuget.org/profiles/mistachkin
SQLite is widely used, event in Android (as a native db engine).
here is what i use to connect. it appears as a Data Connection in Server Explorer.
string con2 = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=" + Application.StartupPath + "\\jobfile_2017.mdf;Integrated Security=True;Connect Timeout=30";
when i first started working with these, i used this source 1
it works on PC's that i have nothing installed (not even office) but as i said i'd be interested to know of any shortcomings of this method
I experiencing same problem and decided to move mdf file to static c:\db directory. Connection string was changed to incorporate new file location (AttachDbFile).
But AttachDbFile has some issues also (by some reason one table in db is inaccesible and error is access denied).
So I decided to move to Sqlite. LocalDb has many issues to work with. I read good note to resolve problem: in command line stop/remove/start name of instance. But it nuissance.
Wish you good luck to work with these db files.
I am creating a C# windows form application, the working can be summarized as users fills some form and data is saved in SQL database. Now the problem I am facing is that I have to deliver this as an executable file to someone. But the problem is database is creating issues as the connection string is not match with that computer. I know that if a distribute projects I can put connection string in app.config and every user can change it according to his/her machine. But i want to make it more convenient for the user not to change the connection string as i am only giving the executable file to client. as i have the connection string in my project is
String ConString = #"Data Source=(LocalDB)\v11.0; AttachDbFilename=D:\Users\khan\Desktop\MyApp\MyApp\Database1.mdf;Integrated Security=True";
So how to make it generic so that the client does not need to change the connections string. Kindly elp me out in this issue.I have searched a lot but still not done with it.
Try to use a Enviroment Variable instead of a fixed path in AttachDbFilename.
For example %APPDATA%\Database1.mdf.
So I have a basic 3-tier application:
Data Access
Business Logic
Presentation
My Data Access layer is a class library, and I'm using Entity Framework and a SQL Server Database File
Say my solution is structured as such
MySolution
\MySolution.Data
\MySolution.Data\App_Data\MySolutionDB.mdf
\MySolution.BusinessLogic
\Presentation
The problem I am trying to solve is that I need to get a folder relative path to the database for the connection string because this project will not always be deployed in into the same folder structure, therefore it is imperative that the connection string is created dynamically based on the relative path.
Could someone offer some assistance on this. please?
P.S. I tried this, but it's not working:
string.Format("Data Source=(LocalDB)\v11.0;AttachDbFilename={0}\\MySolutionDB.mdf;Integrated Security=True", AppDomain.CurrentDomain.GetData("DataDirectory"))
EDIT: Getting this error message, which may be unrelated to the issue...
Connection to the database failed. The connection string is configured
with an invalid LocalDB server name. This may have been set in
'global.asax' by a pre-release version of MVC4. The default connection
factory is now set in web.config so the line in 'global.asax' starting
with 'Database.DefaultConnectionFactory = 'should be removed. See
http://go.microsoft.com/fwlink/?LinkId=243166 for details
Thanks to wdosanjos for pointing out my stupid mistake.
string.Format("Data Source=(LocalDB)\v11.0;AttachDbFilename={0}\\MySolutionDB.mdf;Integrated Security=True", AppDomain.CurrentDomain.GetData("DataDirectory"))
I did not escape \v11.0; it should have been \\v11.0;