Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at

  • Patrick van Kemenade 97 posts 325 karma points
    Apr 09, 2021 @ 12:53
    Patrick van Kemenade

    Create content programmatically using strong types from ModelsBuilder

    Hello All,

    I'm trying to read content from a feed and then save it as Umbraco content.

    I have LiveAppModel and a strongly typed classes fro all my document types.

    When looking into examples on how to save something I get to examples like this. Where everything is done with properties in string. Meaning if a property name will change, get deleted or change datatype then code will break someday in Live environment.

    So there has to be a better way to accomplish this, so if in this case I have an object Person deriving from PublishedContentModel (automatically generated with the Modelsbuilder).

    How do I then set it's properties, since when accessing person.Firstname I have the issue that this property is readonly.

    Regards, Patrick

  • Alex Skrypnyk 6087 posts 23489 karma points MVP 7x admin c-trib
    Apr 09, 2021 @ 14:14
    Alex Skrypnyk

    Hi Patrick

    You can change content only via content service, so you cannot use ModelsBuilder to change the content.

    Published content and ModelsBuilder are only for rendering.

    Content Service for all database changes.



  • Bjarne Fyrstenborg 1275 posts 3921 karma points MVP 7x c-trib
    Apr 09, 2021 @ 15:01
    Bjarne Fyrstenborg

    Hi Patrick

    When using ModelsBuilder you can use a strongly typed syntax if you prefer:

    using ContentModels = Umbraco.Web.PublishedModels;
    var contentService = Services.ContentService;
    var person = contentService.Create("John Doe", parentId, "person"); 
    //person.SetValue("firstName", "John");
    //person.SetValue("lastName", "Doe");
    person.SetValue(ContentModels.Person.GetModelPropertyType(x => x.FirstName).Alias, "John");
    person.SetValue(ContentModels.Person.GetModelPropertyType(x => x.LastName).Alias, "Doe");

    So in case you have this in a class library and the alias had changed, it should give you a compile error.


  • Patrick van Kemenade 97 posts 325 karma points
    Apr 12, 2021 @ 16:02
    Patrick van Kemenade

    @Bjarna, you rock, thanks ! I'll bet many others will find this answer usefull.

  • Bjarne Fyrstenborg 1275 posts 3921 karma points MVP 7x c-trib
    Apr 12, 2021 @ 18:06
    Bjarne Fyrstenborg

    You're welcome :)

    Great you find it useful. You can find more documentation here regarding extending ModelsBuilder:

Please Sign in or register to post replies

Write your reply to: