If you are like me running SQL Server on Linux in a Docker container, you might be wondering how to connect it to your .NET Core application. Here’s how:
-
Make sure that Docker is running by typing
sudo systemctl status docker
and check to make sure that it is active. If it is inactive, typesudo systemctl start docker
. -
Make sure that SQL Server is running by typing
docker ps -a
and check the status column to see whether it is running or not. You can start it by typingsudo docker start CONTAINER ID
whereCONTAINER ID
is the ID of the container listed indocker ps -a
. -
In the
appsettings.Development.json
add the following:
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=MyDatabase;Trusted_Connection=True;User Id=MyUserId;Password=MyPassword"
}
- In
Startup.cs
type the following in theConfigureServices
method:
services.AddDbContext<YourDbContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
});
-
Save the changes in the file.
-
Run your application. Your application should now be able to connect to the database.