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

Mapster:使用带构造函数的映射时,能否为忽略属性设默认值?

Mapster映射时为目标类构造函数缺失的参数指定默认值问题

我尝试使用Mapster将类A映射到类B,其中B包含A没有的Id属性。B采用非默认构造函数初始化(需在构造函数内验证输入数据),常规的.Ignore(e => e.Property)配置方式失效。

演示代码

using Mapster;
using System.Reflection;

var config = new TypeAdapterConfig()
{
    RequireExplicitMapping = false,
    RequireDestinationMemberSource = true,
};

config.Default
    .PreserveReference(true)
    .MapToConstructor(true)
    .Unflattening(false)
    .IgnoreNullValues(false)
    .NameMatchingStrategy(new NameMatchingStrategy
    {
        SourceMemberNameConverter = input => input.ToLowerInvariant(),
        DestinationMemberNameConverter = input => input.ToLowerInvariant(),
    })
    .ShallowCopyForSameType(false);

var ctorToUse = GetConstructor<B>();
config
    .NewConfig<A, B>()
    .Ignore(e => e.Id) // <--------------- 无论是否调用此代码都会失败。
    .MapToConstructor(ctorToUse);

var mapper = new MapsterMapper.Mapper(config);

static ConstructorInfo? GetConstructor<TDestination>()
{
    var parameterlessCtorInfo = typeof(TDestination).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, new Type[0]);

    var ctors = typeof(TDestination).GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
    var validCandidateCtors = ctors.Except(new[] { parameterlessCtorInfo }).ToArray();
    var ctorToUse = validCandidateCtors.Length == 1
        ? validCandidateCtors.First()
        : validCandidateCtors.OrderByDescending(c => c.GetParameters().Length).First();

    return ctorToUse;
}


var a = new A
{
    Text = "test",
};

var docKind = mapper.Map<B>(a); // <------ 此处执行失败。

class A
{
    public string? Text { get; set; }
}

class B
{
    public int Id { get; private set; }
    public string Text { get; private set; }

    public B(int id, string text)
    {
        Id = id;
        Text = text;
    }
}

问题说明

代码中的.Ignore(e => e.Id)存在两难情况:

  • 添加该配置:会因构造函数参数缺失(遗漏Id)报错
  • 不添加该配置:会因Id属性找不到映射源报错

需求询问

是否有办法让Id使用默认值0?我知道可以用.MapWith(a => new B(0, a.Text))手动指定映射逻辑,但希望采用更自动化的方式。

我期望能有如下形式的配置选项,但目前未找到相关功能:

config
    .NewConfig<A, B>()
    .Ignore(e => e.Id, 0) // 为id使用值0
    .Ignore(e => e.Id2, 0) // 为id2使用值0
    .MapToConstructor(ctorToUse);

内容的提问来源于stack exchange,提问作者user2173353

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 21:50:12