-
Create Model Folder and Model Files as Entity Schema for automatically migrations to database sql server.
From this diagram we can assumptions the relations type entyty is "one two many" , one branch can using by many employees. if we're look from json side, we can conclusing the branch table object can be have much emplooyes and the employees table can have one by one branch data.
-
Create Folder Context and make an MyContext.cs File for Entity Framework can be build tables autoamte by the MyContex Script.
-
Before MyContext.cs Script creating in this Context folder, we're must have a few Nuget plugin :
You can install they plugin in the Toold -> Nuget Package Solutions -> Browse, and they plugin it must still install on the old version (V. 5.0.11)
-
After Their plugin had install u can try create MyConetext.cs Files and typing this code in this File looks like this bellow:
-
-
add-migration 'lable migrations'
make sure migration success looks like that bellow:
-
after type migration command we must typing 'database-update' to be implement entity database firsth code into real database our have:
``` > update-database ```
make sure command succcss looks like that bellow:
-
- Create Interface File for Employee with Names "IRepository.cs".
- TYpe on this files like thi bellow
using System; using System.Collections.Generic; namespace APIKARYAWAN.Repository.Interface { public interface IRepository<Entity,Key> where Entity:class { IEnumerable<Entity> Get(); Entity Get(Key key); int Insert(Entity entity); int Update(Entity entity); int Delete(Key key); } }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using APIKARYAWAN.Context;
using APIKARYAWAN.Repository.Interface;
using Microsoft.EntityFrameworkCore;
namespace APIKARYAWAN.Repository // customize like your porject names
{
public class GeneralRepository<Context,Entity, Key> : IRepository<Entity,Key>
where Entity : class
where Context : MyContext
{
private readonly MyContext myContext;
private readonly DbSet<Entity> entities;
public GeneralRepository(MyContext myContext)
{
this.myContext = myContext;
this.entities = myContext.Set<Entity>();
}
public int Delete(Key key)
{
var entity = entities.Find(key);
entities.Remove(entity);
if (entity == null)
throw new ArgumentNullException("entity");
var respond = myContext.SaveChanges();
return respond;
}
public IEnumerable<Entity> Get()
{
return entities.ToList();
}
public Entity Get(Key key)
{
return entities.Find(key);
}
public int Insert(Entity entity)
{
try
{
if (entity == null)
throw new ArgumentNullException("entity");
entities.Add(entity);
return myContext.SaveChanges();
}
catch (Exception)
{
return 0;
}
}
public int Update(Entity entity)
{
if (entity == null)
throw new ArgumentNullException("entity");
myContext.Entry(entity).State = EntityState.Modified;
return myContext.SaveChanges();
}
}
}
using System;
using APIKARYAWAN.Context;
namespace APIKARYAWAN.Repository.Data
{
public class EmployeeRepository :GeneralRepository<MyContext,Role,int>
{
public EmployeeRepository(MyContext myContext):base(myContext)
{
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using APIKARYAWAN.Repository.Interface;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace APIKARYAWAN.Base
{
[Route("api/[controller]")]
[ApiController]
public class BaseController<Entity, Repository, Key> : ControllerBase
where Entity : class
where Repository : IRepository<Entity, Key>
{
private readonly Repository repository;
public BaseController(Repository repository)
{
this.repository = repository;
}
[HttpGet]
public virtual ActionResult<Entity> Get()
{
try
{
var result = repository.Get();
if (result.Count() > 0)
{
// return Ok(result);
return Ok(new { status = StatusCodes.Status200OK, result, message = $" {result.Count()} data Found" });
}
else {
return BadRequest(new { status = StatusCodes.Status204NoContent, result, message = $" [{ControllerContext.ActionDescriptor.ControllerName}] didn't have data" });
}
}
catch (Exception e)
{
return BadRequest(new { status = StatusCodes.Status417ExpectationFailed, message = e.Message });
}
}
[HttpGet("{Key}")]
public ActionResult<Entity> Get(Key key)
{
try
{
var result = repository.Get(key);
if (result != null)
{
return Ok(result);
// return Ok(new { status = StatusCodes.Status200OK, result, message = $" Data Berhasil Didapatkan dengan parameter {key}" });
}
else
{
return Ok(result);
//return BadRequest(new { status = StatusCodes.Status204NoContent, result, message = $"tidak ada indikasi data ditemukan di [{ControllerContext.ActionDescriptor.ControllerName}] dengan paramter {key}" });
}
}
catch (Exception e)
{
return BadRequest(new { status = StatusCodes.Status417ExpectationFailed, errorMessage = e.Message });
}
}
[HttpPost]
public ActionResult<Entity> Post(Entity entity)
{
try
{
var result = repository.Insert(entity);
switch (result)
{
case 1:
return Ok(result);
// return Ok(new { status = StatusCodes.Status201Created, result, message = $"Data Berhasil Tersimpan ke [{ControllerContext.ActionDescriptor.ControllerName}]" });
default:
return Ok(result);
//return BadRequest(new { status = StatusCodes.Status400BadRequest, result, message = $" Data gagal Ditambahkan Sudah ada di dalam database [{ControllerContext.ActionDescriptor.ControllerName}]" });
}
}
catch (Exception e)
{
return BadRequest(new { status = StatusCodes.Status417ExpectationFailed, errors = e.Message });
}
}
[HttpPut]
public virtual ActionResult<Entity> Put(Entity entity)
{
try
{
var result = repository.Update(entity);
switch (result)
{
case 1:
return Ok(result);
// return Ok(new { status = StatusCodes.Status200OK, result, message = $"Data Berhasil Diubah dan Tersimpan ke [{ControllerContext.ActionDescriptor.ControllerName}]" });
default:
return Ok(result);
// return BadRequest(new { status = StatusCodes.Status400BadRequest, result, message = $" Data gagal diubah di[{ControllerContext.ActionDescriptor.ControllerName}]" });
}
}
catch (Exception e)
{
return BadRequest(new { status = StatusCodes.Status417ExpectationFailed, errors = e.Message });
}
}
[HttpDelete("{key}")]
public ActionResult<Entity> Delete(Key key)
{
try
{
var result = repository.Delete(key);
switch (result)
{
case 1:
return Ok(result);
//return Ok(new { status = StatusCodes.Status200OK, result, message = "Data Berhasil Dihapus" });
default:
return Ok(result);
//return BadRequest(new { status = StatusCodes.Status400BadRequest, result, message = $" Data {key} Tidak ditemukan atau sudah dihapus di[{ControllerContext.ActionDescriptor.ControllerName}]" });
}
}
catch (Exception e)
{
return BadRequest(new { status = StatusCodes.Status417ExpectationFailed, errors = e.Message });
}
}
}
}
type this code simillar like this scritp bellow of:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using APIKARYAWAN.Base;
using APIKARYAWAN.Models;
using APIKARYAWAN.Repository.Data;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace APIKARYAWAN.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class EmployeesController : BaseController<Employees,EmployeeRepository,int>
{
private readonly EmployeeRepository employeeRepository;
public EmployeesController(EmployeeRepository repository) : base(repository)
{
this.employeeRepository = repository;
}
}
}
type this code simillar like this scritp bellow of:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using APIKARYAWAN.Base;
using APIKARYAWAN.Models;
using APIKARYAWAN.Repository.Data;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace APIKARYAWAN.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class BranchController : BaseController<Branch, BranchRepository, int>
{
private readonly BranchRepository branchRepository;
public BranchController(BranchRepository repository) : base(repository)
{
this.branchRepository = repository;
}
}
}