Can't access mdf file in desktop application - c#

I need your help.. maybe it's the small task which I am not able to solve but I don't know how to search that on any search engine
I am using an .mdf file (vs 2103) in my WPF login register desktop application.. Everything is working fine, no compilation errors. I inserted some data into the .mdf file by using query in Visual Studio and then try to login through application and it's working fine. Moreover I am also able to register, i.e., insert into .mdf file from the register option of application if I use the "absolute path" of the .mdf file. Problem begins when I try to insert into .mdf file using a "relative path"... it doesn't insert data into the .mdf....I don't know why.
(this absolute path is not working. I have .mdf file in the database folder)
//connection string
connetionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database\Database1.mdf;Integrated Security=True";
//code
SqlCommand sqlCmd;
string sql = null;
SqlConnection sqlCnn = new SqlConnection(connetionString);
try
{
sqlCnn.Open();
sql = "insert into [NewTable] ( Name , Password ) values ('ABC' , '12345')";
sqlCmd = new SqlCommand(sql, sqlCnn);
sqlCmd.ExecuteNonQuery();
sqlCnn.Close();
MessageBox.Show("You have Been Registered");
}
catch (Exception ex)
{
MessageBox.Show("" + ex);
}
It shows the message "You have Been Registered"
but is not visible in .mdf file...
I want to ask..why is it behaving like this....and I want to use the relative path as we cant judge the client system absolute path...what mistake I am doing? how to handle this (i guess self made) issue?

The whole AttachDbFileName= approach is flawed - at best! When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .\bin\debug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The real solution in my opinion would be to
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g. MyDatabase)
connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=MyDatabase;Integrated Security=True
and everything else is exactly the same as before...
Also see Aaron Bertrand excellent blog article Bad habits to kick: Using AttachDbFileName for more in depth explanations and tips

Related

Entity Framework won't save changes in database

When I try to add an item into the database, after running the app the data won't be in the database for long time memory. I don't know why, the connection is good and I already checked it many times.
private void InsertIncomeBtn_Click(object sender, RoutedEventArgs e)
{
float lf = (float)Convert.ToDouble(IncomeText.Text);
MessageBox.Show(lf.ToString());
DateTime date = (DateTime)MovDatePick.SelectedDate;
Movments mv1 = new Movments();
mv1.Sum = lf;
mv1.Date = date.Date;
db.TotalAll.FirstOrDefault().CurrentSum += lf;
db.Movments.Add(mv1);
db.SaveChanges();
IncomeWin.Close();
MainWindow m = new MainWindow();
m.Show();
}
I am using VS 2017 Community and writing a WPF app.
Thank for helping.
I'm assuming (from a lot of previous questions) that you have a SQL Server database, and your connection string most likely contains an AttachDbFileName=..... entry - correct?
If so: the whole AttachDbFileName= approach is flawed - at best! When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .\bin\debug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The real solution in my opinion would be to
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g. YourDatabase)
connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=YourDatabase;Integrated Security=True
and everything else is exactly the same as before...
Also see Aaron Bertrand's excellent blog post Bad habits to kick: using AttachDbFileName for more background info.

C# cannot insert data into SQL Server database

I'm recently new at C# and follow a tutorial on connection to the database, the connection for viewing or SELECT command was ok, I made some revision based on the threads of forums to make my code better, but when I was in INSERT for my SQL Server, I have some problems. I was able to insert the data but when I re-run the program the data that I just inserted earlier was not in the database.
Here is my code on insert
string commandText = "INSERT INTO loginInfo (name, pass, role) VALUES(#name, #pass, #role)";
using (connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(commandText, connection);
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue("#name", textBox1.Text);
command.Parameters.AddWithValue("#pass", textBox2.Text);
command.Parameters.AddWithValue("#role", textBox3.Text);
try
{
command.Connection.Open();
command.ExecuteNonQuery();
}
catch
{
}
finally
{
command.Connection.Close();
}
}
I'm trying to create a simple CRUD but not save the data... please help
If you're using the AttachDbFileName= clause in your connection string, you might have fallen victim to a well-known issue : you might just be looking at the wrong database (file) when checking your data.
When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .\bin\debug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the connection.Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The long-term viable solution in my opinion would be to:
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g. YourDatabase)
connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=YourDatabase;Integrated Security=True
and everything else is exactly the same as before...
Also see Aaron Bertrand's excellent blog post Bad habits to kick: using AttachDbFileName for more background info.

Entity Framework SaveChanges is not working

I have a C# winforms application, and a SQL Server .mdf database file.
I tried to use Entity Framework. It works great when retrieving data from the database, but on calling .SaveChanges() nothing happens. No error, no exception, and no changes saved.
This issue just drives me crazy. I found a bunch of questions with nearly the same issue, but neither of the answers apply to my case.
My code looks like that:
using (World_ParkingEntities context = new World_ParkingEntities())
{
client _client = context.CreateObject<client>();
_client.name = name;
_client.mobile_number = phoneNo;
_client.email = email;
context.AddToclients(_client);
context.SaveChanges();
}
My connection string:
<add name="World_ParkingEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\World_Parking.mdf;Integrated Security=True;User Instance=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" /></connectionStrings>
The whole User Instance and AttachDbFileName= approach is flawed - at best! When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .\bin\debug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint after the context.SaveChanges(); call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The real solution in my opinion would be to
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g. World_Parking)
connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=World_Parking;Integrated Security=True
and everything else is exactly the same as before...

Database file doesn't update

I have created a Windows Forms application that is supposed to add a new record into a database. Now, it adds it successfully and the new data can be used... but when I close the application and start it again, the application acts as if nothing has changed.
The database was created in SQL Server and the application uses the .mdf file it generated.
Here is the method:
private void btnUnos_Click(object sender, EventArgs e)
{
//create an instance of the row to be inserted
PIScarinaDataSet.OsobaRow novaOsoba;
novaOsoba = pIScarinaDataSet.Osoba.NewOsobaRow();
//fill the attributes
novaOsoba.Ime = txtImeOsobe.Text;
novaOsoba.Drzavnost = dobijDrzavu();
novaOsoba.Predstavlja = dobijPredstavnika();
//insert into the database
this.Validate();
this.pIScarinaDataSet.Osoba.Rows.Add(novaOsoba);
this.osobaTableAdapter1.Update(this.pIScarinaDataSet.Osoba);
this.osobaBindingSource1.EndEdit();
}
Since this is what helped you, I will make it an answer:
[S]ince you're using the .MDF created by SQL Server, you need to make sure the "Copy to Output Directory" property on the file is set to "Copy if newer" in Visual Studio. (Or, "Do not copy" if you're going to manually put it in the correct directory.) That is, if you're actually saving the data and this is the issue.
You didn't show us the crucial part - the connection string of your application - but I'm guessing that it will contain something like AttachDbFileName=yourdatabase.mdf somewhere in there.
The whole User Instance and AttachDbFileName= approach is flawed - at best! When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .\bin\debug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The real solution in my opinion would be to
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g. MyDatabase)
connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=MyDatabase;Integrated Security=True
and everything else is exactly the same as before...

Backup Sql Express

I would like to be able to run an on demand backup of a .Net MVC app's SQL Express 2008 database to eg a flash stick plugged into the machine running the app.
I tried
QuickstemDataContext db = new QuickstemDataContext();
string quickstem_path = Path.Combine(save_path, "quickstem.backup");
db.ExecuteCommand(string.Format("BACKUP DATABASE {1} TO DISK = '{0}' WITH COMPRESSION;", quickstem_path, db.Mapping.DatabaseName));
But get the exception
Database 'quickstem' does not exist. Make sure that the name is entered correctly. BACKUP DATABASE is terminating abnormally
I am using the following connection string.
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\quickstem.mdf;Integrated Security=True;User Instance=True"
Do I need to attach the DB using something like Express Management Studio and give it a name etc. Ideally I want to keep the app deploy very simple without having to setup sql management studio etc. Can this attaching be done another way or can a Backup be done with out needing to attach
I tried giving it the full path of the .mdf file instead of the database name but got a syntax error on c:
You'll find that if you add Database=Quickstem to your connection string, your backup code will work just fine.
Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\quickstem.mdf;Integrated Security=True;User Instance=True;Database=Quickstem

Categories

Resources