问题
I create simple example to create question easyer. So in my c# project I create an mdf database with articles. Then I connect database in my program and read values from table articles. It gives me results, but not the latest. If I have one result it showes me this one. Then I go in articles table to add one new article and run program again and in this case program showes me only the first one. But if I "Build solution" it finds all of them.
What I have to do? I wish, that program will have the latest result on startup.
SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");
try
{
cn.Open();
string sqlQuery = "SELECT * FROM Articles";
SqlCommand sqlCommand = new SqlCommand(sqlQuery, cn);
SqlDataReader sqlDataRead = sqlCommand.ExecuteReader();
while (sqlDataRead.Read())
{
MessageBox.Show(Convert.ToString(sqlDataRead["ArticleLabel"]));
}
sqlDataRead.Close();
sqlDataRead.Dispose();
sqlCommand.Cancel();
cn.Close();
}
catch (Exception) { MessageBox.Show("Database error!"); Application.Exit(); }
回答1:
If your MDF file has the property Copy To Output Directory
set to Copy Always
, then every time you build your application a fresh copy of the database file is copied from the project directory to the output Directory (BIN\DEBUG
or BIN\RELEASE
).
Of course this destroy any changes you have made in a previous run of your program
Change the property to Copy if Newer
Also, don't be fooled by what you see in the Server Manager Windows. The connections there could not point to the database in the Output directory but on the database in the Project Directory where you don't write anything.
来源:https://stackoverflow.com/questions/15717655/c-sharp-mdf-database-doesnt-update-on-program-startup