Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Use the Microsoft.Data.SqlClient NuGet package to connect to LocalDB, a lightweight version of SQL Server available on Windows. Use Windows integrated authentication for the examples in this article.
Remarks
To summarize what you can do with LocalDB:
Create and start LocalDB instances with
SqlLocalDB.exe.Use sqlcmd.exe to add and modify databases in a LocalDB instance. For example,
sqlcmd -S (localdb)\myinst.Use the
AttachDBFilenameconnection string keyword to add a database to your LocalDB instance. When usingAttachDBFilename, if you do not specify the name of the database with theDatabaseconnection string keyword, the database will be removed from the LocalDB instance when the application closes.Specify a LocalDB instance in your connection string. For example, your instance name is
myInstance, the connection string would include:Server=(localdb)\myInstance;Database=<database>;Integrated Security=true;Encrypt=true
User Instance=True is not allowed when connecting to a LocalDB database.
For information about installing LocalDB, see SQL Server Express LocalDB.
Programmatically Create a Named Instance
Microsoft.Data.SqlClient on modern .NET doesn't use the .NET Framework system.data.localdb configuration section. Create and start the instance before your application opens a connection:
SqlLocalDB.exe create myInstance
SqlLocalDB.exe start myInstance
Specify the same instance name in the Server connection-string keyword. To attach an existing database file, set AttachDBFilename to the file's full path and set Database to the database name.
For local development with a LocalDB instance that doesn't have a trusted server certificate, use Encrypt=true;TrustServerCertificate=true. This setting encrypts the connection but skips server certificate validation. For remote production connections, use Encrypt=true;TrustServerCertificate=false and configure a server certificate that the client trusts and that matches the server name. For more information, see Encryption and certificate validation in Microsoft.Data.SqlClient.