基于类的转换器,用于对象到对象映射器

时间:2016-07-05 14:39:36

标签: c# type-conversion mapper

我正在寻找一个可以执行以下操作的Object-to-Object映射器:

假设:

class Source
{
    string   FirstName;
    string   LastName;
    DateTime DateOfBirth;
}

class Target
{
    string FirstName;
    string FamilyName;
    string FullName;
    int    Age;
    bool   IsMinor;
}

SourceTarget是不可触及的第三方代码。

我希望能够提供基于会议(名称)的转换器 像这样的课:

class Converter
{
    // field
    public DateTime CurrentDate;  

    // map LastName to FamilyName
    string FamilyName(string lastName) => lastName;

    // map FirstName & LastName to FullName
    string FullName(string firstName, string lastName) => firstName + " " + lastName;

    // map DateOfBirth to Age
    int Age(DateTime dateOfBirth)  
    {
        var days = (CurrentDate - dateOfBirth).TotalDays;
        return (int)(days / 365.25);
    }

    // map DateOfBirth to IsMinor
    bool IsMinor(DateTime dateOfBirth) => Age(dateOfBirth) < 18;  

    // Note: implicit map from FirstName to FirstName     
}

然后能够像这样使用它:

var converter = new Converter {CurrentDate = DateTime.Now};
var mapper    = new Mapper<Source,Target>(converter);  // any mapping lib available for this? 
var targetObject = mapper.Convert(sourceObject);

是否有任何.Net映射库可以做到这一点?
如果是,有人可以举例说明怎么做?

2 个答案:

答案 0 :(得分:1)

以下是使用Automapper进行此操作的一种方法。它只使用静态初始化器,因此映射是应用程序范围的,显然可以实现更好的年龄算法......哦,Source和Target类需要公共属性。

Func<DateTime, int> AgeFunc = (dob) => (int)(DateTime.Now - dob).TotalDays/365;
Mapper.Initialize(cfg =>

    cfg.CreateMap<Source, Target>()
        .ForMember(dest => dest.FamilyName ,m => m.MapFrom(src => src.LastName))
        .ForMember(dest => dest.FullName, m => m.MapFrom(src => src.FirstName + " "  + src.LastName))
        .ForMember(dest => dest.Age, m => m.MapFrom(src => AgeFunc(src.DateOfBirth)))
        .ForMember(dest => dest.IsMinor, m => m.MapFrom(src => AgeFunc(src.DateOfBirth) < 18 ))
);

var peter = new Source() {FirstName = "Peter", LastName="Pan", DateOfBirth=DateTime.Now.AddDays(-7) };
var captain = new Source() {FirstName = "Captain", LastName="Hook", DateOfBirth=DateTime.Now.AddDays(-20000) };

var targetPerter = Mapper.Map<Target>(peter);
var targetCaptain = Mapper.Map<Target>(captain);

答案 1 :(得分:0)

您可以查看名为AutoMapper的工具。

检查这些链接

http://automapper.org/

http://www.codeproject.com/Articles/61629/AutoMapper

希望这有帮助