c# - Automapper 更新字典值

标签 c#

我有一个包含字典的实体,我想要实现的是自动映射器不仅要替换字典,还要更新它的值。

class ExampleClass
{
    public string Name { get; set; }
    public Dictionary<int, string[]> Dictionary { get; set; } 
}

Mapper.CreateMap<ExampleClass, ExampleClass>().ForAllMembers(opt => opt.Condition(srs => !srs.IsSourceValueNull));

var originalClass = new ExampleClass();
originalClass.Name = "Original Class";
originalClass.Dictionary = new Dictionary<int, string[]>
{
    {0, new []{"V1", "V2", "V3"}},
    {1, new []{"V1", "V2", "V3"}},
    {2, new []{"V1", "V2", "V3"}}
};

var newelyCreatedClass = new ExampleClass();
newelyCreatedClass.Dictionary = new Dictionary<int, string[]>
{
    {1, new []{"E1", "E2", "E9"}},
};

Mapper.Map(newelyCreatedClass, originalClass);

在上面的代码中,automapper 奇怪地没有使用 key == 1 更新 Dictionary 元素,而是将整个原始元素替换为在 newelyCreatedClass 中创建的元素。

最佳答案

AutoMapper 只是自动比较并设置值(如果存在),这就是属性被覆盖的原因。但是你可以做的是使用一个名为 Custom Value Resolvers 的自动映射器功能。 .

然后您可以编写一个解析器来检查字典及其值。

public class CustomResolver : IValueResolver<ExampleClass, ExampleClass, Dictionary<int, string[]>>
{
    public Dictionary<int, string[]> Resolve(ExampleClass source, ExampleClass destination, Dictionary<int, string[]> member, ResolutionContext context)
    {
        // logic to iterate through the dictionarys and resolve into dictionary containing values that you want.
    }
}

关于c# - Automapper 更新字典值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21767558/

相关文章:

c# - 长期运行的 Windows 服务中的依赖注入(inject) - Composition root 是正确的想法吗?

c# - 避免跨线程操作

c# - 无法将 Signalr Client 库作为可移植库添加到 Xamarin 项目

c# - “No Application is associated with specified file for this operation”

c# - 检查 Windows 服务状态 - 我需要什么权限

c# - 下载网页最快的 C# 代码

c# - .Net SimpleJson : Deserialize JSON to dynamic object

c# - 强制在来自 NET Web 服务代理类的 SOAP 请求中包含默认值属性属性

c# - 如何将 TabControl 选项卡设置为不可见

c# - 检测图像是否有水印?