Table of Contents

AsDynamic(...)

To make a complex system like the EAV work, the real objects like the IEntity must very very smart and complicated. This would not be fun to use in razor, where you would prefer a simple @Something.Property syntax. This is where AsDynamic(...) comes in.

⚡ The official API docs.

Discover More in the Razor Tutorials

We have an rich series of Razor tutorials. You should really check them out 👍.


How to Use

If you have an IEntity or you're not sure if it's either an IEntity or a IDynamicEntity, just pass it through AsDynamic(...) and the result will be a IDynamicEntity. You can then access the properties with the simple thing.Property syntax.

@inherits Custom.Hybrid.Razor12
@{
    var unknown = App.Data["Default"].List.First(); // this will be an IEntity
    var myThing = AsDynamic(unknown);
}
<div>@myThing.FirstName</div>
Note

Results of AsDynamic are dynamically typed, so you can write .Anything behind it. But the data coming out of it is strong-typed, so Content.Birthday is a real date object.

Tip

IDynamicEntity objects also have some additional properties like EntityId or Parents(...). Check out the API docs.

How it works

AsDynamic has many signatures accepting a variety of input values. It then returns an dynamic object which is either a IDynamicEntity. These are the things AsDynamic can process:

  • a IEntity - this will return a single IDynamicEntity
  • IDynamicEntity - will return the same IDynamicEntity
    this option exists just so you don't have to pre-check what you pass in, making it easier to code for you
  • a string containing JSON - will return a dynamic object
    added in 2sxc 10.20.06
Tip

To use the latest features of 2sxc 12+, make sure your razor file begins with the line
@inherits Custom.Hybrid.Razor12
Otherwise your Razor templates is based on the default, older component code.

Reversing AsDynamic with AsEntity

Check out these docs: AsEntity(...) - Get the Underlying Data

Obsolete use of AsDynamic() for Lists

Warning

In previous versions of 2sxc you'll find AsDynamic(...) also used to convert lists (IEnumerable or DataStreams) into lists. This caused a lot of issues with dynamic code compilation, so in 2sxc 10.20 we introduced AsList(...) for that use case. So if you find that kind of code, it works because...

  • without @inherits Custom.Hybrid.Razor12 in the header, the old calls still work
  • with @inherits Custom.Hybrid.Razor12 in the header, you must use AsList(...)

History

  1. Introduced ca. in 2sxc 1
  2. Modified/added signatures in 2sxc 7
  3. Added the string and DataSource signature in 2sxc 10.20
  4. Introduced AsList to make code more readable for lists 10.20