Skip to main content
 首页 » 编程设计

c#之如何从 Sitefinity 10 中的动态模块集合中检索图像数据

2024年02月27日36虾米哥

我目前正在努力从我的动态模块项目集合中获取图像数据。

我已尝试搜索各种资源,但似乎仍无法找到解决方案。

我有一个 IQueryable 类型,它包含一组动态模块项。然后,我使用 LINQ 选择转换此集合以过滤数据并返回自定义类型。请参阅以下内容:

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") 
}); 

当我尝试上述所有其他属性时,除了返回空 Image 对象的 Image 属性外。但是当我使用单个项目时:

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

以上将返回一个图像对象。

不确定为什么我不能在我的 IQueryable 集合上查询图像数据,而只能在使用单个项目时查询图像数据,有什么想法吗?

谢谢大家!

请您参考如下方法:

基于 Sitefinity 文档 ( 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.

问题是当您查询集合时 collection = (Query to Sitefinity for my custom dynamic module items); ,您没有按主版本过滤。

对于您的情况,有两种解决方案:

1) 只为master过滤集合

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

2) 对于每个 Live 版本,接收它的 Master

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

附言它适用于 collection.FirstOrDefault().GetRelatedItems<Image>("Image")因为集合中的第一个元素是 Master

附言GetRelatedItems 会减慢您的查询速度,这是使用 ContentLinks API 的最佳方式,它会快很多倍。示例:

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 
    } 
}