如何在Umbraco中获取特定类型的强类型文档?
如何将Umbraco的IContent转换为强类型对象?
这是Umbraco开发里很典型的场景——你用ContentService.GetContentOfContentType拿到的是通用的IContent接口实例,自然没法直接通过点语法访问自定义属性。我给你两种靠谱的解决思路:
方法一:手动映射(或用AutoMapper)生成强类型对象
首先你需要定义一个和目标文档类型匹配的强类型类,比如:
public class PensionPoint { public int Id { get; set; } public string Name { get; set; } // 这里添加你文档类型里的自定义属性,比如: public string PointTitle { get; set; } public DateTime PointDate { get; set; } }
接着把IContent的属性值手动映射到这个类的实例上:
var contentType = Services.ContentTypeService.GetContentType(PensionPoint.ModelTypeAlias); var rawPoints = Services.ContentService.GetContentOfContentType(contentType.Id).ToList(); var pensionPoints = rawPoints.Select(content => new PensionPoint { Id = content.Id, Name = content.Name, // 用GetValue方法获取自定义属性,注意对应类型转换 PointTitle = content.GetValue<string>("pointTitle"), PointDate = content.GetValue<DateTime>("pointDate") }).ToList();
如果属性数量多,也可以用AutoMapper简化映射流程,只需要配置一次规则就能自动完成转换。
方法二:用Umbraco Models Builder自动生成强类型模型
Umbraco自带的Models Builder可以根据你的文档类型自动生成对应的强类型类,是最省心的方案:
- 先在Umbraco后台启用Models Builder(设置里可配置),它会自动生成和文档类型同名的类(比如你文档类型别名是
pensionPoint,就会生成PensionPoint类)。 - 之后可以直接转换或查询强类型对象:
// 后台服务层场景:先拿IContent再转换 var contentType = Services.ContentTypeService.GetContentType(PensionPoint.ModelTypeAlias); var rawPoints = Services.ContentService.GetContentOfContentType(contentType.Id).ToList(); var pensionPoints = rawPoints.Select(content => content.As<PensionPoint>()).ToList(); // 前台视图/使用UmbracoHelper的场景:直接查询强类型 var pensionPoints = Umbraco.TypedContentAtXPath($"//{PensionPoint.ModelTypeAlias}") .Cast<PensionPoint>() .ToList();
用As<T>()扩展方法就能把IContent转成对应的强类型模型,之后你就可以直接用pensionPoint.PointTitle这种点语法访问属性了。
内容的提问来源于stack exchange,提问作者ssougnez
相关产品推荐
相关产品推荐

