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

dynamic-linq linq

Question

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[]?)

1
0
9/24/2018 5:29:42 AM

Accepted Answer

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

1
9/25/2018 6:26:00 AM

Popular Answer

I was trying to do some weird thing with reflection and then I stumbled on solution:

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

Hope it helps someone else.



Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow