FSharp.Data.GraphQL icon indicating copy to clipboard operation
FSharp.Data.GraphQL copied to clipboard

Unable to cast object of type to type

Open maarek opened this issue 6 years ago • 1 comments

Description

I am receiving an error when converting a response value. The error I receive is "Unable to cast object of type FooResult to type Foo where FooResult is a value of a discriminated Union. Since it compiles, I am unsure of how to debug the issue or how to diagnose the error.

Repro steps

My 'In type Response is a generated C# class provided by a Protobuf generator and my `Out type Result is a Descriminated Union type such that:

public sealed partial class Response {
  public global::Foo Foo { }
  public GetUnionOneOfCase GetUnionCase { }
let FooType =
    Define.Object<Foo>
        (name = "Foo",
         fields = [ Define.Field("message", String, (fun _ e -> e.Message)) ])

type Result =
  | FooResult of Foo
  | BarResult of Bar

let GetResultType = 
  Define.Union<Response, Result>
    (name = "Response",
     options = [ FooType; BarType ],
     resolveType =
       (fun response ->
       match response.GetUnionCase with
       | Response.GetUnionOneofCase.Foo -> upcase FooType
       | Response.GetUnionOneofCase.Bar -> upcase BarType),
     resolveValue = 
       (fun response ->
       match response.GetUnionCase with
       | Response.GetUnionOneofCase.Foo -> FooResult response.Foo
       | Response.GetUnionOneofCase.Bar -> BarResult response.Bar))

Expected behavior

I expect this to resolve response.Foo as Result.Foo.

Actual behavior

System.Exception: Unable to cast object of type 'FooResult' to type 'Response.Foo'

Related information

  • OSX
  • Dotnet Core

maarek avatar Nov 25 '19 20:11 maarek

I think I see where my confusion lies. Define.Union does not like the DU as the 'Out as it can't handle conversion from the DU. The idea of the resolveValue was to take an 'In as a DU type and pull the values out of it, then box those to an obj? So I removed the Result DU completely, removed the type definition on the Union and boxed the response values and it seems to have worked.

maarek avatar Nov 26 '19 17:11 maarek