You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为AutoMapper的CreateMap配置添加DescriptionAttribute报错求助

为AutoMapper映射添加DescriptionAttribute报错的原因及解决办法

我想给AutoMapper的CreateMap配置添加DescriptionAttribute,编写了以下代码:

public class AppAutoMapper : Profile
{
    public AppAutoMapper()
    {
        [Description("Mapping the JToken to the App ID")]
        CreateMap<JToken, RAFApplicationID>().ForAllMembers(opt =>
        {
            //MAPPING TOKEN TO APP ID MODEL
        });
    }
}

运行时出现错误:

Error   CS7014  Attributes are not valid in this context.

我看到DescriptionAttribute的定义标记了[AttributeUsage(AttributeTargets.All)],说明它可用于任意上下文,为何此处无法正常使用?


报错原因

AttributeTargets.All的含义是该属性可以应用到C#语言允许的所有合法目标元素(比如类、方法、字段、参数、构造函数等),但这不代表能把属性放在任意代码位置。你将属性直接放在CreateMap方法调用语句前方,这个位置不属于任何合法的属性目标元素,因此编译器报错。

解决办法

提供几种可行的实现方式:

1. 将映射逻辑抽为独立方法,给方法添加属性

把单个映射的配置逻辑封装成私有方法,再给这个方法添加DescriptionAttribute,符合属性的合法使用场景:

public class AppAutoMapper : Profile
{
    public AppAutoMapper()
    {
        ConfigureJTokenToRAFApplicationIDMapping();
    }

    [Description("Mapping the JToken to the App ID")]
    private void ConfigureJTokenToRAFApplicationIDMapping()
    {
        CreateMap<JToken, RAFApplicationID>().ForAllMembers(opt =>
        {
            //MAPPING TOKEN TO APP ID MODEL
        });
    }
}

2. 用AutoMapper自定义扩展存储描述

通过扩展方法把描述存入映射的元数据字典,后续可通过反射读取:

public static class AutoMapperDescriptionExtensions
{
    public static IMappingExpression<TSource, TDestination> WithDescription<TSource, TDestination>(
        this IMappingExpression<TSource, TDestination> mapping, string description)
    {
        mapping.Items["Description"] = description;
        return mapping;
    }
}

// 调用方式
CreateMap<JToken, RAFApplicationID>()
    .WithDescription("Mapping the JToken to the App ID")
    .ForAllMembers(opt =>
    {
        //MAPPING TOKEN TO APP ID MODEL
    });

内容的提问来源于stack exchange,提问作者Prosy A.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 03:48:18