Created by referring to Creating Web API with ASP.NET Core. Details of WebAPI are omitted in this article.
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;}
}
}
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
//Only additional parts
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<Models.AuthorContext>(opt => opt.UseSqlServer(Configuration.GetConnectionString("AUTHOR01")));
}
appsettings.json
"ConnectionStrings":{
"AUTHOR01" : "Data Source=db1;Database=Author;User ID=sa;Password=Password0!;"
}
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
Add depends_on and add DB settings
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
docker-compose up
Click here for Source
Recommended Posts