epv epv - 4 months ago 18
JSON Question

JsonResult ASP.NET Entity Framework Core Error

I am creating an app through ASP.Net Core 1.0 and EF Core. I have my models and my view model mapped out with AutoaMapper.

When I create a controller and call it, I get this error:


Error Number:208,State:1,Class:16
Exception thrown: 'System.Data.SqlClient.SqlException' in Microsoft.EntityFrameworkCore.dll
CRAMSCore1.Models.CramsRepository:Error: Error getting complaints
Microsoft.AspNetCore.Mvc.Formatters.Json.Internal.JsonResultExecutor:Information: Executing JsonResult, writing value.


When I check my Sql Profiler on SSMS, I do see that it is querying the database with:


SQL:BatchCompleted SELECT [c].[COMP_ID], [c].[AddrCity], [c].[AddrState], [c].[AddrZip], [c].[Address], [c].[CRORoute_DT]
FROM [Complaints] AS [c] Core .Net SqlClient Data Provider


My Repository looks very simple:

public IEnumerable<COMPLAINT> getAll()
{
try
{
return _context.Complaints
.ToList();
}
catch (Exception ex)
{
_logger.LogError("Error getting complaints", ex);
return null;
}
}


My controller looks like:

[HttpGet("")]
public JsonResult Get()
{
var complaints = _repository.getAll();
var results = Mapper.Map<IEnumerable<ComplaintViewModel>>(complaints);
return Json(complaints);
}

Answer

What does running that SQL manually give you? The error doesn't appear to have anything to do with your JSONResult but more to do with the retrieval of data from SQL via the EF.

I'm also guessing your return should be

return Json(results);
Comments