我正在寻找一个可以执行以下操作的Object-to-Object映射器:
假设:
class Source
{
string FirstName;
string LastName;
DateTime DateOfBirth;
}
和
class Target
{
string FirstName;
string FamilyName;
string FullName;
int Age;
bool IsMinor;
}
Source
和Target
是不可触及的第三方代码。
我希望能够提供基于会议(名称)的转换器 像这样的课:
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映射库可以做到这一点?
如果是,有人可以举例说明怎么做?
答案 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)