-
-
Notifications
You must be signed in to change notification settings - Fork 43
Examples
This page gives some example snippets of how to do different tasks using the
MartinCostello.SqlLocalDb
library.
This snippet shows how to create an instance with a specific name or get that instance if it already exists.
ISqlLocalDbApi localDB = new SqlLocalDbApi();
ISqlLocalDbInstanceManager instance = localDB.GetOrCreateInstance("MyInstance");
This snippet shows to how to create an instance with a random name which is automatically started and then stopped and deleted when the instance is disposed of.
ISqlLocalDbInstanceInfo instance = ...
using TemporarySqlLocalDbInstance instance = localDB.CreateTemporaryInstance();
// Use the instance...
This snippet shows how to obtain a SqlConnection
instance that can be used to
connect to an instance.
ISqlLocalDbInstanceInfo instance = ...
using SqlConnection connection = instance.CreateConnection();
// Use the connection...
This snippet shows how to obtain start an LocalDB instance and then stop it.
ISqlLocalDbApi localDB = new SqlLocalDbApi();
ISqlLocalDbInstanceInfo instance = localDB.GetInstanceInfo("MyInstance");
ISqlLocalDbInstanceManager manager = instance.Manage();
if (!instance.IsRunning)
{
manager.Start();
}
using var connection = new SqlConnection(instance.GetConnectionString());
// Use the connection...
manager.Stop();
This snippet shows an example of an xunit test method that uses a temporary SQL Server LocalDB instance in order to test a data access widget that uses an SQL database.
[Fact]
public static async Task MyDataAccessWidget_Adds_Users_To_Sql_Database()
{
// Arrange
string userName = "john.smith";
using var localDB = new SqlLocalDbApi();
using var instance = localDB.CreateTemporaryInstance();
var target = new MyDataAccessWidget(instance.ConnectionString);
// Act
await target.AddUserAsync(userName);
// Assert
bool actual = await target.UserExistsAsync(userName);
Assert.True(wasUserAdded);
}
There are two projects included in the solution which can be run and debugged out-of-the-box by cloning the repository.
An example using most of the library's functionality can be found in the
MartinCostello.SqlLocalDb.TestApp
project of the SqlLocalDb.sln
solution.
An example of using the API store data for an ASP.NET Core MVC application using SQL Server LocalDB for data storage can be found in the samples.