As far as I remember, since the ModelBuilder was introduced in Umbraco, we have been able to get an alias of any property in the easiest way as below:
The funny thing is that the same solution is still presented in the current Umbraco documentation:
Unfortunately, since Umbraco 10, we need the IPublishedSnapshotAccessor instance, as we can see on the same documentation page:
We had been used to the easiest solution, and we don't like the new one because:
- We have to inject additional IPublishedSnapshotAccessor wherever we want to use it.
- We can't use it in static methods like extensions.
- It expands the GetModelPropertyType method call a little bit.
Therefore, we decided to implement a new easy solution similar to the previous one included in the generated models.
Our solution is based on the ImplementPropertyTypeAttribute, which is added to any property in the generated models.
You can find it in any *.generated.cs files as below:
First of all, we implemented a simple helper as below:
Then implemented an additional required extension for the PropertyInfo class:
We realized really quickly that we need additional method for PublishedElementModel:
Now, we can use it as below:
Final thoughts#
The implemented helper for obtaining Umbraco model property aliases stands out for its ease of use and practicality.
It enhances development efficiency by avoiding complex and error-prone practices like using magic strings🙂.
Additionally, it aligns with best coding practices, fostering a more professional and scalable approach in Umbraco development.
🌐 Explore More: Interested in learning about Umbraco? Explore our blog.
✉️Get in Touch: If you have questions or need assistance with your Umbraco projects, please get in touch with us.