-
-
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 System.Data.SqlLocalDb assembly.
This snippet shows how to create an instance with a specific name or get that instance if it already exists.
ISqlLocalDbProvider provider = new SqlLocalDbProvider();
ISqlLocalDbInstance instance = provider.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.
using (var instance = TemporarySqlLocalDbInstance.Create())
{
// Use the instance...
}
This snippet shows how to obtain a SqlConnection
instance that can be used to connect to an instance.
ISqlLocalDbInstance instance = ...
using (SqlConnection connection = instance.CreateConnection())
{
// Use the connection...
}
This snippet shows an example of a MSTest test method that uses a temporary SQL LocalDB instance in order to test a data access widget that uses an SQL database.
[TestMethod]
public void MyDataAccessWidget_Adds_Users_To_Sql_Database()
{
// Arrange
string userName = "john.smith";
using (var instance = TemporarySqlLocalDbInstance.Create())
{
SqlConnectionStringBuilder builder = instance.CreateConnectionStringBuilder();
MyDataAccessWidget target = new MyDataAccessWidget(builder.ConnectionString);
// Act
target.AddUser(userName);
// Assert
bool wasUserAdded = target.UserExists(userName);
Assert.IsTrue(wasUserAdded, "The user '{0}' was not added to the database.", userName);
}
}
There are two projects included in the solution which can be run and debugged out-of-the-box by cloning the repository.
An example of using most of its functionality of the assembly can be found in the System.Data.SqlLocalDb.TestApp
project of the SqlLocalDb.sln
solution.
An example of using the API to test an ASP.NET MVC application using SQL Server with MSTest can be found in the BlogSample.sln
solution.