如何将 属性 从代码添加到媒体类型?

How to add property from code to media type?

我使用 Umbraco 7.4.12 我需要从代码而不是从 UI.

动态添加 属性 到媒体类型

最好的方法是什么?

应该做这样的事情吗?

下面我将文本字符串 属性 添加到默认图像媒体类型。我什至刚刚测试过它,它正在工作:-)

AddPropertyType 方法有一个重载,允许您在需要时将 属性 添加到给定的 tab/property 组。

protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
    {
        var contentTypeService = ApplicationContext.Current.Services.ContentTypeService;
        var dataTypeService = ApplicationContext.Current.Services.DataTypeService;

        var mediaType = contentTypeService.GetMediaType(1032);

        if (mediaType != null && !mediaType.PropertyTypeExists("myNewPropertyAlias"))
        {
            var dataTypeDefinitions = dataTypeService.GetAllDataTypeDefinitions().ToArray();
            var textStringDataTypeDefinition = dataTypeDefinitions.FirstOrDefault(p => p.Name.ToLower() == "textstring");

            mediaType.AddPropertyType(new PropertyType(textStringDataTypeDefinition) { Name = "My New Property Name", Alias = "myNewPropertyAlias" });

            contentTypeService.Save(mediaType);
        }
    }