Search code examples
c#asp.net-coreasp.net-web-apidapper

How to return dapper dynamic query when asp.net core api method type is IEnumerable<dynamic> and without newtonsoft.json reference


I hope return dapper dynamic query when asp.net core api method type is IEnumerable and without newtonsoft.json reference.

If asp.net core api method type is IEnumerable<dynamic> and using Dapper dynamic query system'll throw exception System.InvalidCastException: Unable to cast object of type '<GetEnumerator>d__9' to type 'System.Collections.IDictionaryEnumerator'.

using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using ServerApp.Helper;
using Dapper;

namespace ServerApp.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class ShDjController : ControllerBase
    {
        [HttpGet]
        public IEnumerable<dynamic> Get()
        {
           using(var cn = DB.GetConnection()){
               return cn.Query(@"select * from table");
           }
        }
    }
}

I know it can be used NewtonSoft.Json to serialize data to json string dealing this problem , but it need more reference, like below code :

        [HttpGet]
        public string Get()
        {
           using(var cn = DB.GetConnection()){
               return JsonConvert.SerializeObject(cn.Query(@"select * from table "));
           }
        }

or

services.AddControllers().AddNewtonsoftJson();

Full error log :

System.InvalidCastException: Unable to cast object of type '<GetEnumerator>d__9' to type 'System.Collections.IDictionaryEnumerator'.
   at System.Text.Json.JsonSerializer.HandleDictionary(JsonClassInfo elementClassInfo, JsonSerializerOptions options, Utf8JsonWriter writer, WriteStack& state)
   at System.Text.Json.JsonSerializer.Write(Utf8JsonWriter writer, Int32 originalWriterDepth, Int32 flushThreshold, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonSerializer.WriteAsyncCore(Stream utf8Json, Object value, Type inputType, JsonSerializerOptions options, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter.WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
   at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter.WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|29_0[TFilter,TFilterAsync](ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

Csproj

  <PropertyGroup>
    <TargetFramework>netcoreapp3.0</TargetFramework>
  </PropertyGroup>

Table Demo Script :

CREATE TABLE Table
    ([col1] int, [col2] int)
;
    
INSERT INTO Table
    ([col1], [col2])
VALUES
    (1, 2),
    (3, 4),
    (5, 6)
;

Solution

  • So i have used the Dapper ORM recently, and this worked perfectly for me

    public string Index()
    {
         using (var cn = new SqlConnection("Data Source=(local);Initial Catalog=Db;Integrated Security=True"))
         {
             return JsonConvert.SerializeObject( cn.Query(@"SELECT * FROM Accounts.[User]"));
         }
    }
    

    I didn't even need to use JsonConvert.SerializeObject

    public IEnumerable<dynamic> Index()
    {
         using (var cn = new SqlConnection("Data Source=(local);Initial Catalog=InstgramWeb;Integrated Security=True"))
         {
               return  cn.Query(@"SELECT * FROM Accounts.[User]");
         }
    }
    

    Whatever error you are having might relate to something else. maybe a specific column? ( Or it could be a version issue ?)

    EDIT: It works for .NET Core 3.1 and not for .NET Core 3.0. Updating the version could solve the issue or otherwise we could use Newtonsoft.Json