Search code examples
c#linqteleriksitefinity

How to retrieve image data from a dynamic module collection in Sitefinity 10?


I am currently struggling with getting image data from my dynamic module item collection.

I have tried searching various resources but still can't seem to find a solution.

I have an IQueryable type which holds a collection of dynamic module items. I then convert this collection using a LINQ select to filter down data and return a custom type. See the following:

IQueryable<DynamicContent> collection = (Query to Sitefinity for my custom dynamic module items);

return collection.Select(b => new CustomType()
{
   Title = b.GetValue<string>("Title"),
   Body = b.GetValue<string>("Body"),
   ExternalLink = b.GetValue<string>("ExternalLink"),
   Image = b.GetRelatedItems<Image>("Image")
});

When I try the above all other properties are populated except the Image property which returns an empty Image object. But when I use a single item:

 collection.FirstOrDefault().GetRelatedItems<Image>("Image") 

The above will return an Image object.

Not sure why I can't query image data on my IQueryable collection but only when using a single item, any ideas?

Thank you all!


Solution

  • Based on Sitefinity documentation (http://docs.sitefinity.com/for-developers-related-data-api):

    When using with the related data API, you need to work with the master versions of both the related data item and the item, to which you are creating a relation.

    Problem is that when you querying collection collection = (Query to Sitefinity for my custom dynamic module items);, you are not filtering by Master version.

    In your case there is two solution:

    1) Filter collection only for master

    collection = collection.Where(i=>i.Status == Telerik.Sitefinity.GenericContent.Model.ContentLifecycleStatus.Master);
    

    2) For each Live version receive it's Master

    var masterItem = dynamicModuleManager.Lifecycle.GetMaster(itemLive);
    

    P.S. It's working for collection.FirstOrDefault().GetRelatedItems<Image>("Image") because very first element in collection is Master

    P.P.S. GetRelatedItems will slow down your query, best way to use ContentLinks API, it is many times faster. Example:

    var contentLinksManager = ContentLinksManager.GetManager();
    var librariesManager= LibrariesManager.GetManager();
    var masterId = data.OriginalContentId; //IF data is Live status or data.Id if is Master status
    var imageFileLink = contentLinksManager.GetContentLinks().FirstOrDefault(cl=>cl.ParentItemId == masterId && cl.ComponentPropertyName == "Image");
    if (imageFileLink != null)
    {
        var image= librariesManager.GetImage(imageFileLink.ChildItemId);
        if (image!= null)
        {
           // Work with image object
        }
    }