最佳实践映射一个对象到另一个 [英] Best Practices for mapping one object to another

查看:112
本文介绍了最佳实践映射一个对象到另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是,什么是我可以在最易维护的方式映射一个对象到另一个的最佳途径。我不能改变的方式,我们所得到的DTO对象设置更加规范化,所以我需要创建一种方法来这个到我们实现自己的目标的。

My question is, what is the best way I can map one object to another in the most maintainable manner. I cannot change the way the Dto object that we are getting is setup to be more normalized so I need to create a way to map this to our implementation of their object.

下面是示例代码来说明我需要发生:

Here is example code to show what I need to happen:

class Program
{
    static void Main(string[] args)
    {
        var dto = new Dto();

        dto.Items = new object[] { 1.00m, true, "Three" };
        dto.ItemsNames = new[] { "One", "Two", "Three" };            

        var model = GetModel(dto);

        Console.WriteLine("One: {0}", model.One);
        Console.WriteLine("Two: {0}", model.Two);
        Console.WriteLine("Three: {0}", model.Three);
        Console.ReadLine();
    }

    private static Model GetModel(Dto dto)
    {
        var result = new Model();

        result.One = Convert.ToDecimal(dto.Items[Array.IndexOf(dto.ItemsNames, "One")]);
        result.Two = Convert.ToBoolean(dto.Items[Array.IndexOf(dto.ItemsNames, "Two")]);
        result.Three = dto.Items[Array.IndexOf(dto.ItemsNames, "Three")].ToString();

        return result;
    }
}

class Dto
{
    public object[] Items { get; set; }
    public string[] ItemsNames { get; set; }
}

class Model
{
    public decimal One { get; set; }
    public bool Two { get; set; }
    public string Three { get; set; }
}



我认为这将是巨大的,如果我有某种映射类的这将需要在模型对象的PropertyInfo,我要转换的类型,而ITEMNAME我想拉了出来。没有人有任何建议,使这一清洁?

I think what would be great is if I had some sort of mapper class that would take in the model objects propertyInfo, the type I want to convert to, and the "itemname" I want to pull out. Does anyone have any suggestions to make this cleaner?

谢谢!

推荐答案

我会选择 AutoMapper ,一个开源和免费的映射库,允许一种类型映射到另一个,根据公约(即公共地图具有相同的名称和相同/导出/敞篷的类型,与许多其他聪明的人一起性质的)。使用非常简单,将让你实现这样的:

I would opt for AutoMapper, an open source and free mapping library which allows to map one type into another, based on conventions (i.e. map public properties with the same names and same/derived/convertible types, along with many other smart ones). Very easy to use, will let you achieve something like this:

Model model = Mapper.Map<Model>(dto);



不知道你的具体要求,但AutoMapper还支持的自定义值解析器的,这将有助于你在写一个通用的执行特定映射的。

Not sure about your specific requirements, but AutoMapper also supports custom value resolvers, which should help you writing a single, generic implementation of your particular mapper.

这篇关于最佳实践映射一个对象到另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆