Question

I'm creating a simple windows forms application using local SQL Server Express database as a data source. During debug the database file is copied into debug folder, everything works fine, but that's not what I want. I'd like to use only one copy of the database file.

Solution I found was hard coding path to the database file in connection string:

Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\db.mdf;Integrated Security=True;User Instance = true

So, is there a more intelligent way of configuring VS to use only one db file, rather than hard coding it's path in connection string?

Était-ce utile?

La solution

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!

The REAL solution in my opinion would be to

  1. install SQL Server Management Studio Express (if you haven't already)

  2. create your database in SSMS Express, give it a logical name (e.g. MyDatabase)

  3. connect to it using its logical database name (given when you create it on the server), and let the server handle all the file-related details; don't mess around with physical 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...

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top