Search code examples
umbracoumbraco7

Get all strongly-typed document of a certain type with Umbraco


I have a web service in which I want to retrieve all document of a certain content type but as strongly typed object. I tried to use this:

var contentType = Services.ContentTypeService.GetContentType(PensionPoint.ModelTypeAlias);
var points = Services.ContentService.GetContentOfContentType(contentType.Id).ToList();

However, I get IContent object on which I can't do Object.Property. How can I retrieve the same items but as strongly-types object ?


Solution

  • You are using the wrong Umbraco API, you need to use the Umbraco Helper to retrieve a published content item rather than the Service API that returns an IContent item.

    var umbracoHelper = 
          new Umbraco.Web.UmbracoHelper(Umbraco.Web.UmbracoContext.Current);
    var pensionPoints = 
          umbracoHelper.TypedContentAtRoot().First().Descendants<PensionPoint>();
    

    Of course, you might be able to get an UmbracoHelper instance directly if your code is within a controller or view.

    Also, please be aware that the code above assumes your content is under a single "home" node.

    Finally, performance may not be very good if your site has a lot of content, in which case you may want to use an XPATH query and cast the result to your class.