c# - AutoMapper 将具有字符串属性的对象转换为具有 URI 属性的对象

标签 c# automapper

我有课

public class A
{
        public string SomeProperty{ get; set; }
        public string URI { get; set; }
}

和另一个类

public class B
    {
        public string SomeProperty { get; set; }
        public Uri URI { get; set; }
    }

我打算使用 AutoMapper 从 A 的对象创建 B 的对象,但由于 URI 的数据类型不同,我确实需要编写一些代码。 我能够通过写作实现我想要的目标

cfg.CreateMap<A, B>()
                .AfterMap((src, targ) =>
                {
                    Uri uri;
                    Uri.TryCreate(src.URI, UriKind.Absolute, out uri);
                    targ.URI = uri;
                });

想知道这是否是最好的方法?

最佳答案

您的解决方案工作正常,但您可以使用 ITypeConverter 创建字符串和 URI 的映射:

public class StringToUriConverter : ITypeConverter<string, Uri>
{
    public Uri Convert(string source, Uri destination, ResolutionContext context)
    {
        Uri.TryCreate(source, UriKind.Absolute, out destination);
        return destination;
    }
}

Depending on the situation, if you were mapping to an existing object, you would have to use the destination parameter and just update it, although this doesn't make much sense for Uri specifically.

然后你只需像这样映射你的类:

Mapper.Initialize(cfg => {

    cfg.CreateMap<string, Uri>().ConvertUsing<StringToUriConverter>();

    cfg.CreateMap<A, B>();
});

Mapper.AssertConfigurationIsValid();

这里的想法是,如果您有任何其他映射需要将字符串转换为 Uri,AutoMapper 现在已经知道如何执行此操作,您不需要显式使用 .ForMember ,也不再是 .AfterMap 了。

这里是 docs for AutoMapper ITypeConverter .

关于c# - AutoMapper 将具有字符串属性的对象转换为具有 URI 属性的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48640305/

相关文章:

c# - 双向映射有什么问题?

c# - Automapper 从 XML 创建对象

c# - 我是否应该在数据库中插入数据期间包括异常处理,即使要插入的数据不是由用户提供的?

c# - WPF 中 RIA 服务的替换

c# - Adcontrol Windows Phone 不显示

c# - Automapper:数组到对象的映射

C# - 序列化和反序列化静态成员

c# - .NET Settings.Reload() 和 Settings.Save() 设置未加载的问题

c# - 如果对象属性存在,为什么 AutoMapper 验证不起作用?

c# - Auto Mapper v4.2.1 - 缺少类型映射配置或不支持的映射