- Docker上にASP.net Core WebAPI環境を構築する(VSCode)の続き。SQLServerとの接続環境を構築。
手順
1.WebAPIの作成
ASP.NET CoreでWebAPIを作成する を参考にして作成。WebAPIの詳細については本記事では割愛。
【作成したWebAPI】
- Model
AuthorModel.cs
namespace webapisqlsv1.Models{
public class AuthorModel {
public int Id { get; set; }
public string Author { get; set; }
public string BookTitle { get; set; }
}
}
AuthorContext.cs
using Microsoft.EntityFrameworkCore;
namespace webapisqlsv1.Models{
public class AuthorContext:DbContext{
public AuthorContext(DbContextOptions<AuthorContext> options)
:base(options){
}
public DbSet<AuthorModel> TblAuthor {get; set;}
}
}
- Controller
AuthorController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using webapisqlsv1.Models;
namespace webapisqlsv1.Controllers
{
[ApiController]
[Route("[controller]")]
public class AuthorController : ControllerBase
{
private readonly ILogger<AuthorController> _logger;
private readonly AuthorContext _context;
public AuthorController(ILogger<AuthorController> logger, AuthorContext context)
{
_logger = logger;
_context = context;
}
[HttpGet]
public IEnumerable<AuthorModel> Get()
{
return _context.TblAuthor.ToArray();
}
}
}
- Startup.cs
Startup.cs
//追加部分のみ
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<Models.AuthorContext>(opt => opt.UseSqlServer(Configuration.GetConnectionString("AUTHOR01")));
}
- appsettings.json 追加部分のみ
appsettings.json
"ConnectionStrings":{
"AUTHOR01" : "Data Source=db1;Database=Author;User ID=sa;Password=Password0!;"
}
2.Docker環境の作成
- DB用のフォルダを作成しDB用のDockerfileを作成
Dockerfile
FROM mcr.microsoft.com/mssql/server:2017-latest
ENV ACCEPT_EULA=Y
ENV MSSQL_SA_PASSWORD=Password0!
ENV MSSQL_PID=Express
ENV MSSQL_COLLATION=Japanese_CI_AS
ENV MSSQL_LOG_DIR=/MSSQL/log
ENV MSSQL_DATA_DIR=/MSSQL/data
ENV MSSQL_BACKUP_DIR=/MSSQL/backup
ENV MSSQL_MASTER_DATA_FILE=/MSSQL/master.mdf
ENV MSSQL_MASTER_LOG_FILE=/MSSQL/mastlog.ldf
EXPOSE 1433
- docker-compose.ymlを編集
depends_onを追加しDBの設定を追加する
docker-compose.yml
# Please refer https://aka.ms/HTTPSinContainer on how to setup an https developer certificate for your ASP .NET Core service.
version: '3.4'
services:
webapisqlsv1:
image: webapisqlsv1
container_name: apisqlsv1
build:
context: .
dockerfile: Dockerfile
ports:
- 5001:5000
depends_on:
- db
db:
image: mssqldb
container_name: sqlsv1
hostname: db1
build:
context: ./db/
dockerfile: Dockerfile
volumes:
- C:\Docker\SQLServer\DB:/MSSQL
ports:
- 1433:1433
3.コマンド実行&結果
docker-compose up
ソースはこちら