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 dockerand 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 -aand check the status column to see whether it is running or not. You can start it by typingsudo docker start CONTAINER IDwhereCONTAINER IDis the ID of the container listed indocker ps -a. -
In the
appsettings.Development.jsonadd the following:
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=MyDatabase;Trusted_Connection=True;User Id=MyUserId;Password=MyPassword"
}
- In
Startup.cstype the following in theConfigureServicesmethod:
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.