问题
I have packed a WPF C# application that is using a database.
However, when I install the packaged application it is using the database I created at the start through visual studio (.mdf) rather than creating another one.
The whole purpose of packaging the application was so that I could share it on other computers, so I was install it I need it to create a new database for that instance of the application.
Is there a way to accomplish this? Is there a property I need to set to say that the database is a local instance? Or force the package to create a new one on installation?
Any help would be much appreciated.
Thanks.
回答1:
Just been in the middle of doing this myself, one thing I would suggest is using SQL Compact Edition makes the process a lot easier, but if it's too late in the process at the moment then stick with the current database, However I do not know if the below method works with an MDF file.
How are you deploying the application on the client machine? does the users machine have sql installed?
The first thing you need to do is go to the properties of your MDF and ensure copy to output directory is set to copy if newer and build action is set to content.
If you're using a setup project to install the application then you need to make sure in project, application properties, publish, application files that you're mdf is in the list and is set to Data File auto, required and include.
and right click on the "Application Folder" in the installers file system, then add, project output, file contents
Finally change the connection string in your code so that it reads
using ( SqlCeConnection sqlCon = new SqlCeConnection( @"Data Source=|DataDirectory|\App.sdf;Persist Security Info=False;" )
or if you're not using compact Edition
using ( SqlConnection sqlCon = new SqlConnection( @"Data Source=|DataDirectory|\App.mdf;Persist Security Info=False;" )
^using "DataDirectory" means that you don't care where the user puts the application, you will always get the right file
before you run and change your database to compact, it doesnt support a lot of things a proper sql database will.
After all this, you may still encounter errors with permissions and because its quite long winded I might have missed out a step so just comment if you need more?
EDIT If the user does not have either sql server or sql Compact, your easiest solution would be to require them to install SQL CE or there is a way of using DLLs that do the same thing but I couldn't get that to work
the link for that is here http://msdn.microsoft.com/en-us/library/aa983326.aspx
回答2:
Make sure your db is deployed client side and change the connection string in the application to point to it.
来源:https://stackoverflow.com/questions/10752295/packaging-a-c-sharp-application-with-a-database