Data not saving permanently to SQL table

后端 未结 5 1048
梦谈多话
梦谈多话 2020-12-06 15:14

I am using C# for a WPF application in Visual Studio Express 2012. I followed the tutorial found here. I created a testDb.mdf local Service-based database. I

5条回答
  •  粉色の甜心
    2020-12-06 15:39

    It is a common scenario. You have a connection string that uses the substitution string |DataDirectory|. In a desktop application this directory is usually the same directory where your program runs. Inside Visual Studio, your program runs in the BIN\DEBUG (or x86 variant) directory. Thus the Visual Studio copies your MDF file from the project directory to the BIN\DEBUG folder. You add records to this copy, not to the one in the project folder. However, the Visual Studio Server Explorer window has a connection that points to the Project Folder database that, of course, remains empty.

    You could add another connection to the Server Explorer pointing to the folder BIN\DEBUG and check that your database has been updated or not.

    To complicate the matter, there is the property Copy to the Output Directory associated with the MDF file. If this property is set to Copy Always everytime you start a new session within Visual Studio, the file is copied again from the project folder to the output directory (BIN\DEBUG) overwriting the copy already there with a new empty one. So the first run succeds, the second one fails.
    The symptoms that you observed are a clear sign of this situation.

    Simply change the property Copy to the Output directory to Copy if newer, the code works well.
    (Peraphs it is too early, but remember to change your query to a parameterized query. As is, you could break your code simply inserting a single quote in the txtName textbox like O'Malley, not to mention the Sql Injection hack)

提交回复
热议问题