I am new to .NET and one of my first goals is creating an API in .NET Core 6. In this API I need to call a TVF with 2 parameters in my GET method in order to return the result in json.
I found many replies to this question and people always use SqlQuery
method like this:
_context.Database.SqlQuery<model>("select * from myFunction()")
However, it looks like SqlQuery
is missing in .NET Core 6. Another approach was using a DbDataReader
like this:
var command = _context.Database.GetDbConnection().CreateCommand();
command.CommandText = "SELECT * FROM myFunction()";
DbDataReader reader = await command.ExecuteReaderAsync();
In this case I get an error
The connection's current state is closed
I am a bit confusing at this point because my other methods work fine, my context is working. Anyway, I am not sure if this is a good approach.
Any help would be appreciated.
This is my entire controller:
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using API.Models;
namespace API.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class EmpleadoController : ControllerBase
{
private readonly DBContext _context;
public EmpleadoController(DBContext context)
{
_context = context;
}
// GET: api/Empleado
[HttpGet]
public async Task<ActionResult<IEnumerable<Empleado>>> GetEmpleados()
{
return await _context.Empleados.ToListAsync();
}
// GET: api/Empleado/5
[HttpGet("{id}")]
public async Task<ActionResult<Empleado>> GetEmpleado(int id)
{
var empleado = await _context.Empleados.FindAsync(id);
if (empleado == null)
{
return NotFound();
}
return empleado;
}
// GET: api/Empleado/5/2022
[HttpGet("{id},{year}")]
public async Task<ActionResult<List<DiaCalendario>>> GetCalendario(int id, int year)
{
var command = _context.Database.GetDbConnection().CreateCommand();
command.CommandText = "SELECT * FROM dbo.getCalendarioEmpleado(" + year + "," + id +")";
DbDataReader reader = await command.ExecuteReaderAsync();
if (reader != null)
{
List<DiaCalendario> Calendario = new List<DiaCalendario>();
while (reader.Read())
{
DiaCalendario dia = new DiaCalendario();
dia.Fecha = (DateOnly)reader["Fecha"];
dia.TipoDia = (int)reader["TipoDia"];
dia.PT = (bool)reader["PT"];
dia.Horas = (decimal)reader["Horas"];
Calendario.Add(dia);
}
return Calendario;
}
else
{
return NotFound();
}
}
private bool EmpleadoExists(int id)
{
return _context.Empleados.Any(e => e.EmpleadoId == id);
}
}
}