使用Automapper和Underscores进行映射

时间:2013-10-16 21:46:34

标签: c# automapper

在下面的示例中,我只是想让Test_Person_Name.FirstName映射到TestPersonFlattened中的某些内容(任何内容)。在这一点上,考虑到我沉浸在这里的时间量,我不会太依赖目的地属性名称。我只是想让它起作用。

public class Test_Person
{
    public Test_Person_Name Test_Person_PublicName { get; set; }
}

public class Test_Person_Name
{
    public string FirstName { get; set; }

    public string LastName { get; set; }
}

public class TestPersonFlattened
{
    public string Test_Person_PublicNameFirstName { get; set; } // What do I call this property?
}

AutoMapper.Mapper.CreateMap<Test_Person, TestPersonFlattened>();

AutoMapper.Mapper.AssertConfigurationIsValid();

似乎Test_Person_PublicNameFirstName应该可以工作,但我在AssertConfigurationIsValid()上得到一个例外。我还尝试了TestPersonPublicNameFirstName,Test_Person_PublicName_FirstName作为目标属性名称。

重命名源属性名称是不利的,因为源库在许多其他项目中使用。此外,ForMember()调用并不理想,但如果没有其他选择,我会这样做。

1 个答案:

答案 0 :(得分:0)

一种方法是简单地从PublicNameFirstName类的TestPersonFlattened属性中省略“Test_Person_”,并使用RecognizePrefixes()使其成为AutoMapper忽略“Test_Person_” “在尝试映射属性名称时。

以下代码成功:

public partial class App : Application
{
    public App()
    {
        Mapper.Initialize(cfg =>
        {
            cfg.RecognizePrefixes("Test_Person_");
            cfg.CreateMap<Test_Person, TestPersonFlattened>();
        }); 
        Mapper.CreateMap<Test_Person, TestPersonFlattened>();

        Mapper.AssertConfigurationIsValid();
    }
}
public class Test_Person
{
    public Test_Person_Name Test_Person_PublicName { get; set; }
}

public class Test_Person_Name
{
    public string FirstName { get; set; }

    public string LastName { get; set; }
}

public class TestPersonFlattened
{
    public string PublicNameFirstName { get; set; } // This is what I call this property!
}
相关问题