使AutoMapper自动映射前缀属性 [英] Make AutoMapper automatically map prefixed properties

查看:198
本文介绍了使AutoMapper自动映射前缀属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望AutoMapper自动映射这样的成员:

I want AutoMapper to map automatically Members like this:

class Model 
{
    public int ModelId { get; set; }
}

class ModelDto 
{
    public int Id { get; set; }
}

在这里,我会做一个

CreateMap<Model, ModelDTO>()
    .ForMember(x => x.Id, e => e.MapFrom(x => x.ModelId)

但是,如何使AutoMapper自动执行映射?我的大部分课程都是这样.主键的格式为:ClassName +"Id".

But, how could I make AutoMapper do the mapping automatically? Most of my classes are like that. The Primary key is in the form: ClassName + "Id".

我已经尝试过了,但是不起作用:

I've tried with this, but it doesn't work:

class Program
{
    static void Main(string[] args)
    {
        Mapper.Initialize(exp =>
        {
            exp.CreateMap<User, UserDto>();
            exp.ForAllPropertyMaps(map => map.DestinationProperty.Name.Equals("Id"), (map, expression) => expression.MapFrom(map.SourceType.Name + "Id"));
        });


        var user = new User() { UserId = 34};
        var dto = Mapper.Map<UserDto>(user);
    }
}

public class UserDto
{
    public int Id { get; set; }
}

class User
{
    public int UserId { get; set; }
}

推荐答案

是的,代码看起来很合理,但无法正常工作.这是因为它在计算属性映射之后运行.在这种情况下,没有名称,因为名称不匹配.我的坏:)试试

Yes, the code looks reasonable, but it doesn't work. That's because it runs after the property maps are computed. And there are none in this case, because the names don't match. My bad :) Try

exp.ForAllMaps( (typeMap, mappingExpression) => 
    mappingExpression.ForMember("Id", o=>o.MapFrom(typeMap.SourceType.Name + "Id"))
);

这篇关于使AutoMapper自动映射前缀属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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