需要从实体获取 2sxc 字段类型

问题描述

在对上一个问题 Is there a way to Clone one or many Entities (records) in Code 进行所有处理后,我想对其进行清理并使其更有用/可重用。到目前为止,我正在决定如何使用内容类型字段名称复制/添加字段,因此在属性的foreach中使用attribute.Key。我需要的是知道实体字段的类型;表示字符串、数字、超链接、实体等

所以我想要像 if(AsEntity(original).FieldType == "HyperLink") { do this thing } 之类的东西。我已经浏览了 API 文档,但还没有发现如何获取信息。可能吗?

我确实发现 attribute.Value 有一个类型,我可以用它来回答大多数问题,但 Hyperlink 和 String 都显示为 System.String。

以下是按顺序排列的字符串、超链接、实体和数字:

atts: ToSic.Eav.Data.Attribute`1[System.String]    
atts: ToSic.Eav.Data.Attribute`1[System.String]    
atts: ToSic.Eav.Data.Attribute`1[ToSic.Eav.Data.EntityRelationship]    
atts: ToSic.Eav.Data.Attribute`1[System.Nullable`1[System.Decimal]]

那么是否有一种方法可以从实体或其属性或对象/方法/属性的其他路径中获取作为字段类型名称的答案?或者是否有某种我可以使用的包装器可以让我处理(转换为/从)超链接?我对其他想法持开放态度。由于 fields.Add() 因“FieldType”而异,这将非常有用。

解决方法

这有点简单,但由于 Razor 的动态特性,需要更多的代码。这是一个示例代码,应该可以满足您的需求:

@using System.Collections.Generic;
@using System.Linq;
@using ToSic.Eav.Data;

var type = AsEntity(Content).Type;
var attributes = type.Attributes as IEnumerable<IContentTypeAttribute>;
var typeOfAwards attributes.First(t => t.Name == "Awards").Type; // this will return "Entity"

我在这里为您创建了一个快速示例:https://2sxc.org/dnn-tutorials/en/razor/data910/page