Skip to content

Instantly share code, notes, and snippets.

@georgekosmidis
Last active July 16, 2020 08:32
Show Gist options
  • Save georgekosmidis/73174bbb3656f52273101c7fc3da4b10 to your computer and use it in GitHub Desktop.
Save georgekosmidis/73174bbb3656f52273101c7fc3da4b10 to your computer and use it in GitHub Desktop.
"ConnectionStrings": {
"MariaDbConnectionString": "server=localhost;user id=root;password=root;database=aspnetcore.mariadb"
}
dotnet new webapi
dotnet add package Pomelo.EntityFrameworkCore.MySql
dotnet build
public partial class MariaDbContext : Microsoft.EntityFrameworkCore.DbContext
{
public MariaDbContext(DbContextOptions<MariaDbContext> options)
: base(options)
{
}
public virtual DbSet<WeatherForecastDataModel> WeatherForecasts { get; set; }
}
public sealed class MariaDbWeatherForecastService : IMariaDbWeatherForecastService
{
private readonly MariaDbContext _dbContext;
public MariaDbWeatherForecastService(MariaDbContext dbContext)
{
_dbContext = dbContext;
}
public async Task<int> Delete(int id)
{
try
{
_dbContext.WeatherForecasts.Remove(
new WeatherForecastDataModel
{
Id = id
}
);
return await _dbContext.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
return 0;
}
}
public async Task<IEnumerable<WeatherForecastDataModel>> FindAll()
{
return await _dbContext.WeatherForecasts.ToListAsync();
}
public async Task<WeatherForecastDataModel> FindOne(int id)
{
return await _dbContext.WeatherForecasts.FirstOrDefaultAsync(x => x.Id == id);
}
public async Task<int> Insert(WeatherForecastDataModel forecast)
{
_dbContext.Add(forecast);
return await _dbContext.SaveChangesAsync();
}
public async Task<int> Update(WeatherForecastDataModel forecast)
{
try
{
_dbContext.Update(forecast);
return await _dbContext.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
return 0;
}
}
}
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContextPool<MariaDbDbContext>(options => options
.UseMySql(
Configuration.GetConnectionString("MariaDbConnectionString"),
mySqlOptions => mySqlOptions.ServerVersion(new Version(10, 5, 4), ServerType.MariaDb)
)
);
services.AddControllers();
}
services.AddScoped<IMariaDbWeatherForecastService, MariaDbWeatherForecastService>();
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private readonly ILogger<WeatherForecastController> _logger;
private readonly IMariaDbWeatherForecastService _forecastDbService;
public WeatherForecastController(ILogger<WeatherForecastController> logger, IMariaDbWeatherForecastService forecastDbService)
{
_forecastDbService = forecastDbService;
_logger = logger;
}
[HttpGet]
public async Task<IEnumerable<WeatherForecastDataModel>> Get()
{
return await _forecastDbService.FindAll();
}
[HttpGet("{id}", Name = "FindOne")]
public async Task<ActionResult<WeatherForecastDataModel>> Get(int id)
{
var result = await _forecastDbService.FindOne(id);
if (result != default)
return Ok(result);
else
return NotFound();
}
[HttpPost]
public async Task<ActionResult<WeatherForecastDataModel>> Insert(WeatherForecastDataModel dto)
{
if (dto.Id != null)
{
return BadRequest("Id cannot be set for insert action.");
}
var id = await _forecastDbService.Insert(dto);
if (id != default)
return CreatedAtRoute("FindOne", new { id = id }, dto);
else
return BadRequest();
}
[HttpPut]
public async Task<ActionResult<WeatherForecastDataModel>> Update(WeatherForecastDataModel dto)
{
if (dto.Id == null)
{
return BadRequest("Id should be set for insert action.");
}
var result = await _forecastDbService.Update(dto);
if (result > 0)
return NoContent();
else
return NotFound();
}
[HttpDelete("{id}")]
public async Task<ActionResult<WeatherForecastDataModel>> Delete(int id)
{
var result = await _forecastDbService.Delete(id);
if (result > 0)
return NoContent();
else
return NotFound();
}
}
public class WeatherForecastDataModel
{
public int? Id { get; set; }
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
public string Summary { get; set; }
}
CREATE TABLE `weatherforecasts` (
`Id` INT(11) NOT NULL AUTO_INCREMENT,
`Date` DATETIME NULL DEFAULT NULL,
`TemperatureC` TINYINT(4) NULL DEFAULT NULL,
`Summary` TEXT(65535) NULL DEFAULT NULL COLLATE 'latin1_general_ci',
PRIMARY KEY (`Id`)
)
COLLATE='latin1_general_ci'
ENGINE=InnoDB
;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment