Attaching database to my project [closed]

2020-07-31 07:11发布

问题:

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 7 years ago.

In my C# program I have a big problem:

I add an SQL server database named "Behgozin_DB" to my project. I do the following steps for adding the database:

  1. In my SQL server management studio I detach my database
  2. In my visual studio from Data menu I add new data source
  3. My Connection String is:

Data Source=(local);AttachDbFilename=|DataDirectory|\DB_Behgozin.mdf;Integrated Security=True

Everything is OK but when I insert something into my database after closing the application , I can not see any data. But when I right click on my tables in my visual studio server explorer menu and choose show table data, my application reads the whole table of data completely!

Another problem is after working with this app, even it can not read its own data in table.

Its a C# project in Visual Studio 2010 SQL Server 2008.

回答1:

Your database file has 2 copies. One is in your project and the other is in bin\debug. In design time you edit the one in your project. Each time your project changes and you build it, the project database file is overwriting the file in bin\debug, and this file you're updating in run-time.

In order to solve that you have three options:

  1. Use only the file in bin\debug. Set the project database file copy options to "Never" (in the properties window), show all files of the project and add the bin\debug database file to the server explorer. Caution: If you accidently delete the bin\debug folder all your changes are gone. Manually copy the database file from bin\debug to the project folder when you change it.

  2. Put the file in your sql server folder and not in your project. When deploying, change the connection string and copy the database from server.

  3. Replace "|DataDirectory|" macro with the absolute path to the project database file. When deploying, just change it back to "|DataDirectory|"