Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting Object/Dynamic to Anonymous Type

I have an EF query which returns an anonymous type of several joined tables. I pass this to another function as a dynamic. Is there any way to cast the dynamic to an anonymous type of known anonymous type? If there is a way to do this, I would assume that passing it as an Object is better than a dynamic, is this correct?

...
var appts = (from a in dbc.tblAppt join b in dbc.tblApptTypes on a.Type equals b.Type select new {a, b}).ToList();
If (appts.Any())
    ProcessAppts(appts);
}

void ProcessAppts(dynamic appts)
{
    var AnonTypeAppts = appts as (new {tblAppt, tblApptTypes}); // This bit here
}
like image 948
sonnyJim Avatar asked Sep 12 '25 18:09

sonnyJim


1 Answers

No. Anonymous types are... anonymous. You can't cast a variable to an anonymous type, like you tried in your code. And preferably you shouldn't pass them around though other methods. They should be kept inside. And you really shouldn't use dynamic for this.

I suggest to create a 'real' type which you can pass around to another method.

like image 187
Patrick Hofman Avatar answered Sep 15 '25 09:09

Patrick Hofman