visit
version: '3.4'
services:
dockersqlserver:
image: ${DOCKER_REGISTRY-}dockersqlserver
build:
context: .
dockerfile: DockerSqlServer/Dockerfile
version: '3.4'
services:
db:
image: "mcr.microsoft.com/mssql/server:2017-latest"
environment:
- ACCEPT_EULA=Y
- SA_PASSWORD=1Secure*Password1
dockersqlserver:
image: ${DOCKER_REGISTRY-}dockersqlserver
build:
context: .
dockerfile: DockerSqlServer/Dockerfile
depends_on:
- db
PLEASE NOTE: The SA_PASSWORD field seems to have some strict criteria on what the password needs to contain. I couldn't find the exact requirements, but it would be advisable to use a long password using upper and lowercase characters, numbers and special characters.
For the purpose of following this tutorial the password I have provided does fulfill these criteria. If your password doesn't meet the requirements, later when you come to run the container, you will get a SQLException complaining that the application couldn't log in as the SA user. If you get this exception, try modifying the password and trying again. depends_on:
- db
"ConnectionStrings": {
"AppDbContext": "Server=db;Database=AppDbContext;User=sa;Password=1Secure*Password1;"
}
A CRUD application is one with the basic functionality to Create, Read, Update, and Delete. In this app we will create a basic Note model and create a basic REST API to perform these CRUD functions. We will use EF Core to interact with the SQL Server Docker container.
The full working solution can be found in . First, make sure that you have the Docker containers set up as described above. Then we will start by creating the Note model:// Models/Note.cs
namespace DockerSqlServer.Models
{
public class Note
{
public int Id { get; set; }
public string Text { get; set; }
}
}
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Design
Microsoft.EntityFrameworkCore.Tools
using DockerSqlServer.Models;
using Microsoft.EntityFrameworkCore;
namespace DockerSqlServer
{
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions options) : base(options)
{
}
public DbSet<Note> Notes { get; set; }
}
}
services.AddDbContext<AppDbContext>(options => options
.UseSqlServer(Configuration.GetConnectionString("AppDbContext")));
add-migration AddNoteEntity
public async static Task Main(string[] args)
{
var host = CreateHostBuilder(args).Build();
using var scope = host.Services.CreateScope();
var services = scope.ServiceProvider;
try
{
var dbContext = services.GetRequiredService<AppDbContext>();
if (dbContext.Database.IsSqlServer())
{
dbContext.Database.Migrate();
}
}
catch (Exception ex)
{
var logger = scope.ServiceProvider.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred while migrating or seeding the database.");
throw;
}
await host.RunAsync();
}
// Controllers/NotesController.cs
using DockerSqlServer.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;
namespace DockerSqlServer.Controllers
{
[ApiController]
[Route("[controller]")]
public class NotesController
{
private readonly AppDbContext _db;
public NotesController(AppDbContext db)
{
_db = db;
}
[HttpGet]
public async Task<IActionResult> Get()
{
var notes = await _db.Notes.ToListAsync();
return new JsonResult(notes);
}
[HttpGet("{id}")]
public async Task<IActionResult> Get(int id)
{
var note = await _db.Notes.FirstOrDefaultAsync(n => n.Id == id);
return new JsonResult(note);
}
[HttpPost]
public async Task<IActionResult> Post(Note note)
{
_db.Notes.Add(note);
await _db.SaveChangesAsync();
return new JsonResult(note.Id);
}
[HttpPut]
public async Task<IActionResult> Put(int id, Note note)
{
var existingNote = await _db.Notes.FirstOrDefaultAsync(n => n.Id == id);
existingNote.Text = note.Text;
var success = (await _db.SaveChangesAsync()) > 0;
return new JsonResult(success);
}
[HttpDelete]
public async Task<IActionResult> Delete(int id)
{
var note = await _db.Notes.FirstOrDefaultAsync(n => n.Id == id);
_db.Remove(note);
var success = (await _db.SaveChangesAsync()) > 0;
return new JsonResult(success);
}
}
}
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace DockerSqlServer
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddDbContext<AppDbContext>(options => options
.UseSqlServer(Configuration.GetConnectionString("AppDbContext")));
services.AddSwaggerGen();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
c.RoutePrefix = string.Empty;
});
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
Previously published at