Это контроллер моей таблицы tblUser (выбрать, создать, обновить, Удалить, все обычное) в API:
Код: Выделить всё
UserController:
[Route("api/[controller]")]
[ApiController]
public class tblUserController : ControllerBase
{
private readonly QDbContext _qDbContext;
public tblUserController(QDbContext qDbContext) => _qDbContext = qDbContext;
[HttpGet]
public ActionResult Get()
{
return _qDbContext.tblUsers;
}
[HttpGet("{id}")]
public async Task GetById(int id)
{
return await _qDbContext.tblUsers.Where(x => x.ID == id).SingleOrDefaultAsync();
}
[HttpPost]
public async Task Create(tblUser user)
{
await _qDbContext.tblUsers.AddAsync(user);
await _qDbContext.SaveChangesAsync();
return CreatedAtAction(nameof(GetById), new { id = user.ID }, user);
}
[HttpPut]
public async Task Update(tblUser user)
{
_qDbContext.tblUsers.Update(user);
await _qDbContext.SaveChangesAsync();
return Ok();
}
[HttpDelete("{id}")]
public async Task Delete(int id)
{
var userGetByIdResult = await GetById(id);
if (userGetByIdResult.Value is null)
return NotFound();
_qDbContext.Remove(userGetByIdResult.Value);
await _qDbContext.SaveChangesAsync();
return Ok();
}
}
Мне очень не хотелось повторять одно и то же для каждой таблицы, поэтому я создал родительский класс, который получает тип TEntity и делает то же самое:
р>
Код: Выделить всё
DbController:
[Route("api/[controller]")]
[ApiController]
public class DbController : ControllerBase where TEntity : class
{
private readonly DbContext _context;
private readonly DbSet _dbSet;
public DbController(DbContext context)
{
_context = context;
_dbSet = _context.Set();
}
[HttpGet]
public async Task Get()
{
return await _dbSet.ToListAsync();
}
[HttpGet("{id}")]
public async Task GetById(int id)
{
TEntity? entity = await _dbSet.FindAsync(id);
return entity == null ? (ActionResult)NotFound() : (ActionResult)entity;
}
[HttpPost]
public async Task Create(TEntity entity)
{
_ = await _dbSet.AddAsync(entity);
_ = await _context.SaveChangesAsync();
return CreatedAtAction(nameof(GetById), new { id = entity.GetType().GetProperty("ID")?.GetValue(entity) }, entity);
}
[HttpPut("{id}")]
public async Task Update(int id, TEntity entity)
{
TEntity? existingEntity = await _dbSet.FindAsync(id);
if (existingEntity == null)
{
return NotFound();
}
_context.Entry(existingEntity).CurrentValues.SetValues(entity);
_ = await _context.SaveChangesAsync();
return Ok();
}
[HttpDelete("{id}")]
public async Task Delete(int id)
{
TEntity? entity = await _dbSet.FindAsync(id);
if (entity == null)
{
return NotFound();
}
_ = _dbSet.Remove(entity);
_ = await _context.SaveChangesAsync();
return Ok();
}
}
Код: Выделить всё
[Route("api/[controller]")]
[ApiController]
public class tblUsersController : DbController
{
public tblUsersController(QDbContext context) : base(context)
{
}
}
Код: Выделить всё
DbApiClientService:
namespace QF.API.Client
{
public class DbApiClientService
{
private readonly HttpClient _httpClient;
public DbApiClientService(ApiClientOptions apiClientOptions)
{
_httpClient = new HttpClient();
_httpClient.BaseAddress = new System.Uri(apiClientOptions.ApiBaseAddress);
}
public async Task GetItems()
{
string endpoint = GetEndpointName();
return await _httpClient.GetFromJsonAsync($"/api/{endpoint}");
}
public async Task GetById(int id)
{
string endpoint = GetEndpointName();
return await _httpClient.GetFromJsonAsync($"/api/{endpoint}/{id}");
}
public async Task SaveItem(T item)
{
string endpoint = GetEndpointName();
await _httpClient.PostAsJsonAsync($"/api/{endpoint}", item);
}
public async Task UpdateItem(T item)
{
string endpoint = GetEndpointName();
await _httpClient.PutAsJsonAsync($"/api/{endpoint}", item);
}
public async Task DeleteItem(int id)
{
string endpoint = GetEndpointName();
await _httpClient.DeleteAsync($"/api/{endpoint}/{id}");
}
private string GetEndpointName()
{
return typeof(T).Name;
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/787 ... all-tables