Search code examples
linqdynamic-linq

Cast result to custom class with System.Linq.Dynamic.Core


I am trying to typecast result to custom class with System.Linq.Dynamic.Core but I am getting exception:

System.InvalidCastException: 'Unable to cast object of type '<>f__AnonymousType0`2[System.Int32,System.Int32]' to type 'MyClass

My code is:

class MyClass
{
    public int LangId { get; set; }
    public int GroupId { get; set; }
}

var fields = "new(LangId AS LangId,TranslateId AS GroupId)";
context.Table.Select(fields).ToDynamicListAsync<MyClass>();

Did I wrongly understand what should generic method ToDynamicListAsync do, or I have another error in code somewhere else?

Can I do that? (typecast dynamic[] result to custom_object[]?)


Solution

  • I think you can also use this code?

    var rows = await context.Table.Select<MyClass>(fields).ToDynamicListAsync<MyClass>();
    

    This extension method is also defined in DynamicQueryableExtensions.cs