Я надеюсь вернуть dapper Dynami c запрос, когда asp. net тип метода core api - IEnumerable и без newtonsoft. json ссылка.
If asp. net core Тип метода api - IEnumerable<dynamic>
, и при использовании Dapper dynamic query
система выдаст исключение 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");
}
}
}
}
Я знаю, что его можно использовать NewtonSoft.Json
для сериализации данных в строку json, решающую эту проблему , но для этого нужна дополнительная ссылка, например, код ниже:
[HttpGet]
public string Get()
{
using(var cn = DB.GetConnection()){
return JsonConvert.SerializeObject(cn.Query(@"select * from table "));
}
}
или
services.AddControllers().AddNewtonsoftJson();
Полный журнал ошибок:
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>
Скрипт демонстрации таблицы:
CREATE TABLE Table
([col1] int, [col2] int)
;
INSERT INTO Table
([col1], [col2])
VALUES
(1, 2),
(3, 4),
(5, 6)
;