0

I have a Entity with an Enum property:

[Table("SOP10100")]
public class Order : INotifyPropertyChanged
{
    [Column("SOPTYPE")]
    public OrderType Soptype { get; set; }
    ...
}

I have an Enum:

public enum OrderType : short
{
    Quote = 1,
    Order = 2,
    Invoice = 3,
    Return = 4,
    BackOrder = 5,
    FulfillmentOrder = 6
}

In my DbContext OnModelCreating I have:

modelBuilder.Entity<Order>()
    .Property(p => p.Soptype)
    .HasConversion(v => v.ToString(), v => (OrderType)Enum.Parse(typeof(OrderType), v));

... I got the example from Value Conversions.

But I am getting a System.InvalidOperationException when I run the query in Swagger.

System.InvalidOperationException: An error occurred while reading a database value for property 'Order.Soptype'. The expected type was 'DataAccessLayer.Models.Enums.OrderType' but the actual value was of type 'System.Int16'.

 ---> System.InvalidCastException: Unable to cast object of type 'System.Int16' to type 'System.String'.
   at Microsoft.Data.SqlClient.SqlBuffer.get_String()
   at Microsoft.Data.SqlClient.SqlDataReader.GetString(Int32 i)
   at lambda_method56(Closure , QueryContext , DbDataReader , ResultContext , SingleQueryResultCoordinator )

   --- End of inner exception stack trace ---

   at lambda_method56(Closure , QueryContext , DbDataReader , ResultContext , SingleQueryResultCoordinator )
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)
   at EcommerceWebAPI.Services.OrderService.GetAllOrdersAsync() in D:\Projects\NewEcommerce\NewEcommerce\Services\OrderService.cs:line 27
   at EcommerceWebAPI.Controllers.OrdersController.GetAllOrdersAsync() in D:\Projects\NewEcommerce\NewEcommerce\Controllers\OrdersController.cs:line 27
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Logged|12_1(ControllerActionInvoker invoker)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   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 EcommerceWebAPI.Helpers.JwtMiddleware.Invoke(HttpContext context, IUserService userService) in D:\Projects\NewEcommerce\NewEcommerce\Helpers\JwtMiddleware.cs:line 34
   at Microsoft.AspNetCore.ResponseCaching.ResponseCachingMiddleware.Invoke(HttpContext httpContext)
   at Serilog.AspNetCore.RequestLoggingMiddleware.Invoke(HttpContext httpContext)
   at EcommerceWebAPI.Startup.<>c.<<Configure>b__5_1>d.MoveNext() in D:\Projects\NewEcommerce\NewEcommerce\Startup.cs:line 174

--- End of stack trace from previous location ---

   at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

Any help will be appreciated.

Randy
  • 1,137
  • 16
  • 49
  • Can you share the migration file for the Order entity. Did you create the migration before adding the enum-string conversion? – j-petty Jul 20 '21 at 23:29
  • @j-petty I am not using Migrations. I cannot modify these Tables. – Randy Jul 20 '21 at 23:32
  • Does `HasConversion()` work instead? It seems like your query is returning an int16 but EF is expecting a string – devNull Jul 20 '21 at 23:41
  • @devNull No, that only changed the Error Message to Can't convert Int32 from Int16. – Randy Jul 20 '21 at 23:49
  • @Randy Then maybe `HasConversion()`? – devNull Jul 20 '21 at 23:51
  • @devNull Regarding your last, I get no errors but it is still only displaying the value not the Enum text. – Randy Jul 20 '21 at 23:58
  • 1
    @Randy Displaying where? In the Swagger UI? Or in an API endpoint response? If it's the former, you can [enable that](https://stackoverflow.com/q/36452468/5803406) in the startup config – devNull Jul 21 '21 at 00:11
  • @devNull I tried using Postman. Both PostMan and Swagger UI display the value not the text. – Randy Jul 21 '21 at 00:26
  • @devNull I had to decorate my Property with `[EnumDataType(typeof(OrderType))]` and `[JsonConverter(typeof(StringEnumConverter))]` like from the your linked comment. You wanna put that in an Answer and I will accept it. – Randy Jul 21 '21 at 00:36

0 Answers0