所有其他答案都好得多(我对每个答案都投了赞成票)。
但我想在这里发布的是一个快速游乐场,您可以在 C# 程序模式下复制并直接粘贴到LinqPad中,并在不影响实际代码的情况下发挥您的想法。
将所有转换移动到 TyperConverter 类的另一件很棒的事情是,您的转换现在是可单元测试的。:)
在这里,您会注意到模型和视图模型几乎相同,除了一个属性。但是通过这个过程,正确的属性被转换为目标对象中的正确属性。
将此代码复制到LinqPad 中,您可以在切换到 C# 程序模式后使用播放按钮运行它。
void Main()
{
AutoMapper.Mapper.CreateMap<UserModel, UserViewModel>().ConvertUsing(new UserModelToUserViewModelConverter());
AutoMapper.Mapper.AssertConfigurationIsValid();
var userModel = new UserModel
{
DifferentPropertyName = "Batman",
Name = "RockStar",
Roles = new[] {new RoleModel(), new RoleModel() }
};
var userViewModel = AutoMapper.Mapper.Map<UserViewModel>(userModel);
Console.WriteLine(userViewModel.ToString());
}
// Define other methods and classes here
public class UserModel
{
public string Name {get;set;}
public IEnumerable<RoleModel> Roles { get; set; }
public string DifferentPropertyName { get; set; }
}
public class UserViewModel
{
public string Name {get;set;}
public IEnumerable<RoleModel> Roles { get; set; } // notice the ViewModel
public string Thingy { get; set; }
public override string ToString()
{
var sb = new StringBuilder();
sb.AppendLine(string.Format("Name: {0}", Name));
sb.AppendLine(string.Format("Thingy: {0}", Thingy));
sb.AppendLine(string.Format("Contains #{0} of roles", Roles.Count()));
return sb.ToString();
}
}
public class UserModelToUserViewModelConverter : TypeConverter<UserModel, UserViewModel>
{
protected override UserViewModel ConvertCore(UserModel source)
{
if(source == null)
{
return null;
}
//You can add logic here to deal with nulls, empty strings, empty objects etc
var userViewModel = new UserViewModel
{
Name = source.Name,
Roles = source.Roles,
Thingy = source.DifferentPropertyName
};
return userViewModel;
}
}
public class RoleModel
{
//no content for ease, plus this has it's own mapper in real life
}
结果来自Console.WriteLine(userViewModel.ToString());
:
Name: RockStar
Thingy: Batman
Contains #2 of roles