gpt4 book ai didi

c# - AutoMapper - 如何将参数传递给配置文件?

转载 作者:太空宇宙 更新时间:2023-11-03 23:09:19 26 4
gpt4 key购买 nike

我想使用自动映射器在我的公共(public)数据契约(Contract)和我的 BD 模型之间进行映射。我需要将一个字符串参数传递到我的 MapProfile 中,并从我的属性中获取描述(本例中为“代码”)。例如:

public class Source
{
public int Code { get; set; }
}

public class Destination
{
public string Description { get; set; }
}

public class Dic
{
public static string GetDescription(int code, string tag)
{
//do something
return "My Description";
}
}

public class MyProfile : Profile
{

protected override void Configure()
{
CreateMap<Destination, Source>()
.ForMember(dest => dest.Description,
opt => /* something */
Dic.GetDescription(code, tag));
}
}

public class MyTest
{

[Fact]
public void test()
{
var source = new Source { Code = 1};

var mapperConfig = new MapperConfiguration(config => config.AddProfile<MyProfile>());
var mapper = mapperConfig.CreateMapper();

var result = mapper.Map<Destination>(source, opt => opt.Items["Tag"] = "AnyTag");

Assert.Equal("My Description", result.Description);
}
}

最佳答案

这可以使用 CustomResolver

来实现
public class MyProfile : Profile
{

protected override void Configure()
{
CreateMap<Destination, Source>()
.ForMember(dest => dest.Description, opt => opt.ResolveUsing<CustomResolver>().FromMember(src => src.Code));
}
}

public class CustomResolver : IValueResolver
{
public ResolutionResult Resolve(ResolutionResult source)
{
var code = (int)source.Value;

var tag = source.Context.Options.Items["Tag"].ToString();

var description = Dic.GetDescription(code, tag);

return source.New(description);
}
}

关于c# - AutoMapper - 如何将参数传递给配置文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39964857/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com