Automapper公约 [英] Automapper Convention

查看:144
本文介绍了Automapper公约的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

时,可以使用 Automapper 设置一个惯例,这样的地图不必被手的情况下创建,其中实体您。被映射到刚刚已经说视图模型追加

Is is possible with Automapper to setup a convention so that maps do not have to be created by hand for situations where the entity you are mapping to just has say "ViewModel" appended.

作为一个例子,我宁可不要设置如下图:

As an example I would rather not have to setup the following map:

Mapper.CreateMap<Error, ErrorViewModel>();



我明白,如果投影需要,我需要创建一个自定义的地图,但有一个约定, 。创建地图将是很好的。

I understand if projection is required that I would need to create a custom map, but having a convention to create maps would be nice.

推荐答案

您需要使用 Mapper.DynamicMap< TDest>(源)映射。

正如你可以在下面的例子中看到,它会自动从源匹配属性映射到目的地。

As you can see in the example below, it automatically maps the matching properties from source to destination.

using AutoMapper;
using System.Diagnostics;

class Program
{
    static void Main(string[] args)
    {
        var source = new Foo {Value = "Abc"};
        var destination = Mapper.DynamicMap<FooViewModel>(source);

        Debug.Assert(source.Value == destination.Value);
    }
}

public class Foo
{
    public string Value { get; set; }
}

public class FooViewModel
{
    public string Value { get; set; }
}

这篇关于Automapper公约的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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