Skip to content

Examples

Martin Costello edited this page Jan 18, 2022 · 7 revisions

Code Examples

Introduction

This page gives some example snippets of how to do different tasks using the MartinCostello.SqlLocalDb library.

Create an Instance

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");

Create a Throw-away Instance

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...

Connect to an 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...

Start and Stop an Instance

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();

Use an Instance as Part of a Unit Test

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);
}

Runnable Examples

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.