Todo => task zero

Video Tutorial
ไฟล์ Solution และ src โฟล์เดอร์
Todo.API โปรเจค
Create Project Type
Project architecture
Todo location
namespace Todo.API.Models
{
[Serializable]
public class Todo
{
public Guid Id { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public string Description { get; set; }
public Status Status { get; set; }
public bool IsActive { get; set; }
public bool IsDelete { get; set; }
public string CreatedBy { get; set; }
public DateTime CreatedOn { get; set; }
public string UpdatedBy { get; set; }
public DateTime UpdatedOn { get; set; }
public string DeletedBy { get; set; }
public DateTime DeletedOn { get; set; }
}
}
namespace Todo.API.Enums
{
public enum Status : byte
{
Pending = 0,
Doing = 1,
Success = 2,
Cancel = 3
}
}
using Microsoft.EntityFrameworkCore;

namespace Todo.API.Connections
{
public class ApplicationDbContext : DbContext
{
protected readonly IConfiguration Configuration;
protected readonly DbContextOptions<ApplicationDbContext> ContextOptions;

public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}

public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, IConfiguration configuration) :
base(options)
{
ContextOptions = options;
Configuration = configuration;
}
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Models.Todo>().ToTable("tb_todos");
modelBuilder.Entity<Models.Todo>().HasKey(k => k.Id);
modelBuilder.Entity<Models.Todo>().Property(p => p.Id).ValueGeneratedOnAdd();
modelBuilder.Entity<Models.Todo>().Property(p => p.StartDate).HasColumnType("datetime2")
.HasColumnName("start_date");
modelBuilder.Entity<Models.Todo>().Property(p => p.EndDate).HasColumnType("datetime2")
.HasColumnName("end_date");
modelBuilder.Entity<Models.Todo>().Property(p => p.Description).HasColumnName("descriptions");
modelBuilder.Entity<Models.Todo>().Property(p => p.Status).HasColumnName("status");
modelBuilder.Entity<Models.Todo>().Property(p => p.IsActive).HasColumnName("is_active");
modelBuilder.Entity<Models.Todo>().Property(p => p.IsDelete).HasColumnName("is_delete");
modelBuilder.Entity<Models.Todo>().Property(p => p.CreatedBy).HasColumnName("created_by");
modelBuilder.Entity<Models.Todo>().Property(p => p.CreatedOn).HasColumnType("datetime2")
.HasColumnName("created_on");
modelBuilder.Entity<Models.Todo>().Property(p => p.UpdatedBy).HasColumnName("updated_by").IsRequired(false);
modelBuilder.Entity<Models.Todo>().Property(p => p.UpdatedOn).HasColumnType("datetime2")
.HasColumnName("updated_on").IsRequired(false);
modelBuilder.Entity<Models.Todo>().Property(p => p.DeletedBy).HasColumnName("deleted_by").IsRequired(false);
modelBuilder.Entity<Models.Todo>().Property(p => p.DeletedOn).HasColumnType("datetime2")
.HasColumnName("deleted_on").IsRequired(false);
}
ApplicationDbContext.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
{
options
.ConfigureWarnings(warnings =>
warnings.Throw(RelationalEventId.QueryPossibleExceptionWithAggregateOperatorWarning))
.UseSqlServer(Configuration.GetValue<string>("DefaultConnection"), sqlOptions =>
{
sqlOptions.EnableRetryOnFailure(5, TimeSpan.FromSeconds(30), null!);
sqlOptions.MigrationsAssembly(
typeof(ApplicationDbContext).GetTypeInfo().Assembly.GetName().Name);
});
});
services.AddControllers();
}
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"DefaultConnection": "Server=localhost;Database=TodoDatabase;User Id=<user>;Password=<password>;"
}
InitailaDatabase
Todo database
TodoController
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Todo.API.Connections;

namespace Todo.API.Controllers
{
[ApiController]
[Produces("application/json")]
[Route("api/[controller]/[action]")]
public class TodoController : ControllerBase
{
private readonly ApplicationDbContext _context;

public TodoController(ApplicationDbContext context)
{
_context = context;
}

[HttpGet]
public async Task<IActionResult> GetAllAsync()
{
var result = await _context.Set<Models.Todo>().Where(s => !s.IsDelete).ToListAsync();
return Ok(result);
}

[HttpGet("{id}")]
public async Task<IActionResult> GetByIdAsync(Guid id)
{
var result = await _context.Set<Models.Todo>().FirstOrDefaultAsync(s => s.Id == id);

if (result != null)
{
return Ok(result);
}

return NotFound();
}

[HttpPost]
public async Task<IActionResult> CreateAsync(Models.Todo request)
{
request.CreatedOn = DateTime.UtcNow;
request.UpdatedBy = request.CreatedBy;
request.UpdatedOn = DateTime.UtcNow;

await _context.Set<Models.Todo>().AddAsync(request);
if (await _context.SaveChangesAsync() > 0)
{
return Ok();
}

return BadRequest();
}

[HttpPut("{id}")]
public async Task<IActionResult> UpdateAsync(Guid id, Models.Todo request)
{
var exist = await _context.Set<Models.Todo>().FirstOrDefaultAsync(s => s.Id == id);
if (exist == null) return NotFound();

exist.StartDate = request.StartDate;
exist.EndDate = request.EndDate;
exist.Description = request.Description;
exist.Status = exist.Status;
exist.UpdatedBy = exist.UpdatedBy;
exist.UpdatedOn = DateTime.UtcNow;
exist.IsActive = request.IsActive;

_context.Set<Models.Todo>().Update(exist);

if (await _context.SaveChangesAsync() > 0)
{
return Ok();
}

return BadRequest();
}

[HttpDelete("{id}")]
public async Task<IActionResult> DeleteAsync(Guid id, string deletedBy)
{
var exist = await _context.Set<Models.Todo>().FirstOrDefaultAsync(s => s.Id == id);
if (exist == null) return NotFound();

exist.IsDelete = true;
exist.DeletedBy = deletedBy;
exist.DeletedOn = DateTime.UtcNow;

_context.Set<Models.Todo>().Update(exist);

if (await _context.SaveChangesAsync() > 0)
{
return Ok();
}

return NotFound();
}
}
}
Get all record
Create new record
Get all record
Record detail
Update exist record
Delete exist record
https://github.com/VatthanachaiW/todo-project

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
วัฒนชัย วงศ์ประเสริฐ

วัฒนชัย วงศ์ประเสริฐ

Rogue Planet

More from Medium

Best Java Testing Tools

Managing multiple Git profiles in .gitconfig

Everything about git commands 👨‍💻️

Git Git Versioning.!!!