How do you unit test ASP.NET Core MVC Controllers that return anonymous objects?

Original idea from this answer with a more generic approach. Using a custom DynamicObject as a wrapper for inspecting the value via reflection there was no need to add the InternalsVisibleTo public class DynamicObjectResultValue : DynamicObject, IEquatable<DynamicObjectResultValue> { private readonly object value; public DynamicObjectResultValue(object value) { this.value = value; } #region Operators public static bool … Read more

razor view with anonymous type model class. It is possible?

The short answer is that using anonymous types is not supported, however, there is a workaround, you can use an ExpandoObject Set your model to @model IEnumerable<dynamic> Then in the controller from p in db.Articles.Where(p => p.user_id == 2) select new { p.article_id, p.title, p.date, p.category, /* Additional parameters which arent in Article model */ … Read more

How does ToString on an anonymous type work?

With anonymous objects… The compiler generates an internal sealed class that models the anonymous type. The anonymous type is immutable; all the properties are read only. That class contains overrides of Equals() and GetHashCode() that implement value semantics. In addition, the compiler generates an override of ToString() that displays the value of each of the … Read more

Anonymous Type vs Dynamic Type

You seem to be mixing three completely different, orthogonal things: static vs. dynamic typing manifest vs. implicit typing named vs. anonymous types Those three aspects are completely independent, they have nothing whatsoever to do with each other. Static vs. dynamic typing refers to when the type checking takes place: dynamic typing takes place at runtime, … Read more

How to dynamic new Anonymous Class?

Anonymous types are just regular types that are implicitly declared. They have little to do with dynamic. Now, if you were to use an ExpandoObject and reference it through a dynamic variable, you could add or remove fields on the fly. edit Sure you can: just cast it to IDictionary<string, object>. Then you can use … Read more