2 years ago
#11848
Jefferson Pardo
How Can I Get a single JSON object in an ASP.NET Core 5 Web API using a stored procedure in SQL Server with Entity Framework Core 5.0?
I’m trying to create a service that responds with a JSON of a single instance of an object.The idea is that from a user ID (id_user
) it returns a single record from the user table like this:
{
"id": 1,
"urlImage": " https://i.pinimg.com/474x/d0/e4/e4/d0e4e45662096e2aacdb0b72da38ed85.jpg",
"name1": " Jefferson",
"lastName1": "Pardo",
"city": " Bogotá",
"country": "string",
"nickname": " Jeffer",
"demonym_fem": "colombian",
}
When I try to run this endpoint
[Route("GetBasicProfile/")]
[ApiController]
public class BasicProfileController : ControllerBase
{
private readonly dbjeffContext _context;
public BasicProfileController(dbjeffContext context)
{
_context = context;
}
// GET: api/BasicProfile
[HttpGet]
public async Task<ActionResult<IEnumerable<BasicProfile>>> GetBasicProfile(int id)
{
SqlParameter param1 = new SqlParameter(@"id_user", id);
string StoredProc = "EXEC GetBasicProfile @id_user";
var BasicProfileReturn = await _context.BasicProfile.FromSqlRaw(StoredProc, param1).ToListAsync();
return BasicProfileReturn;
}
}
I get this error
500
UndocumentedSystem.InvalidOperationException: The required column 'LastName1' was not present in the results of a 'FromSql' operation.
I think my problem is in the FromSqlRaw
function, but I have already tried this way too
[HttpGet("{id}")]
public async Task<BasicProfile[]> GetBasicProfile(int id)
{
BasicProfile[] BasicsProfiles;
SqlParameter param1 = new SqlParameter(@"id_user", id);
BasicsProfiles = _context.BasicProfile.FromSqlRaw("exec GetBasicProfile @id_user", param1).ToArray();
return BasicsProfiles;
}
Help!! I'm desperate T__T
The stored procedure in SQL Server looks like this:
CREATE OR ALTER PROCEDURE [dbo].[GetBasicProfile]
(@id_user int)
AS
BEGIN
SET NOCOUNT ON
SELECT
id,
url_image url_image,
u.name1 name1,
u.last_name1 last_name1,
u.city city,
(SELECT DISTINCT gen_femenino
FROM country
WHERE id = u.id_country) demonym_fem
FROM
userr u
WHERE
id = @id_user;
END
In .NET 5, I have this class
public class BasicProfile
{
public int? Id { get; set; }
public string? UrlImage { get; set; }
public string? Name1 { get; set; }
public string? LastName1 { get; set; }
public string? City { get; set; }
public string? demonym_fem { get; set; }
}
And this context class
public partial class dbjeffContext: DbContext
{
public dbjeffContext() { }
public dbjeffContext(DbContextOptions<dbjeffContext> options)
:base(options) { }
public virtual DbSet<BasicProfile> BasicProfile { get; set; }
}
sql-server
asp.net-web-api
entity-framework-core
asp.net5
ef-core-5.0
0 Answers
Your Answer