Search code examples
c#sql-servervisual-studio-2017localdbportable-database

Separate file for SQL database


Using Visual Studio 2017, for a C# project, how do I create my SQL database in a separated and portable file?


Solution

  • The Visual Studio "native" database is LocalDB. This information goes out of date quickly but here is the current situation, summarised from the link below

    https://learn.microsoft.com/en-us/sql/database-engine/configure-windows/sql-server-express-localdb?view=sql-server-ver15

    • LocalDB can be installed through the Visual Studio installer
    • The SqlLocalDB.exe utility lets you manage LocalDB (i.e. start/stop/create/delete)
    • LocalDB cannot be managed remotely via SQL Management Studio.
    • One "automatic" instance of LocalDB exists for every version of LocalDB installed on the user's computer. This is public and is created and managed automatically for the user
    • The easiest way to use LocalDB is to connect to the automatic instance owned by the current user by using the connection string Server=(localdb)\MSSQLLocalDB;Integrated Security=true. To connect to a specific database by using the file name, connect using a connection string similar to Server=(LocalDB)\MSSQLLocalDB;Integrated Security=true;AttachDbFileName=D:\Data\MyDB1.mdf

    I've never managed to find clear instructions on how this should be deployed. Suffice to say you should be able to easily install LocalDB on the target machine and deploy your MDF file for it to use.

    If you would care to expand on your use case, there might be other options.

    I have a software that I will run to gather data. This software will, hopefully in a near future, allow to consult the data. But if I am the "gatherer" the "reader" will be someone else. I need to send the data there.

    For example you could use a cloud database (Azure SQL would be the visual studio native platform). You don't need to install anything, it's automatically backed up. It's publicly accessible to anyone (and can be locked down). Downside is it's about $8.00 USD a month for 250Gb