不需要创建对象来再次初始化属性。使用自动映射器。例子
创建地址类
public class Address
{
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string PostalCode { get; set; }
public string Country { get; set; }
}
创建客户类
public class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public Address HomeAddress { get; set; }
public string GetFullName()
{
return string.Format("{0} {1}", FirstName, LastName);
}
}
在Controller中,创建一个动作方法
方法 - 1(未创建映射时)
public class AutoMapperController : Controller
{
public ActionResult Index()
{
List<Customer> customers = new List<Customer>();
customers.Add(
new Customer
{
Email = "a@s.com",
FirstName = "F1",
LastName = "L1",
HomeAddress = new Address
{
Address1 = "A1",
Address2 = "A2",
City = "C1",
Country = "Co1",
PostalCode = "P1"
}
});
AutoMapper.Mapper.CreateMap<Customer, CustomerListViewModel>();
IList<CustomerListViewModel> viewModelList =
AutoMapper.Mapper.Map<IList<Customer>,
IList<CustomerListViewModel>>(customers);
return View(viewModelList);
}
}
现在,如果您看到下面的结果......我们在 Customer 类中有数据,并且在完成 AutoMapping CustomerListViewModel 类之后填充......
方法 - 2 创建映射时
创建一个名为 MyMappings 的类并使用以下代码定义映射。
public class MyMappings : Profile
{
public const string NameOfProfile = "ContactDataProfile";
public override string ProfileName
{
get
{
return NameOfProfile;
}
}
protected override void Configure()
{
CreateMaps();
}
private static void CreateMaps()
{
Mapper.CreateMap<Customer, CustomerListViewModel>()
.ForMember(dest => dest.Email, opt => opt.MapFrom(src => src.Email))
.ForMember(dest => dest.FullName, opt => opt.MapFrom(src => src.FirstName + "." + src.LastName))
.ForMember(dest => dest.HomeAddressCountry, opt => opt.MapFrom(src => src.HomeAddress))
.IgnoreAllNonExisting();
Mapper.AssertConfigurationIsValid();
}
}
以下是您想要在某些类属性之间发送映射时所需的类
public static class AutoMapperExtensions
{
public static IMappingExpression<TSource, TDestination>
IgnoreAllNonExisting<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression)
{
var sourceType = typeof(TSource);
var destinationType = typeof(TDestination);
var existingMaps = Mapper.GetAllTypeMaps().First(x => x.SourceType == sourceType && x.DestinationType == destinationType);
foreach (var property in existingMaps.GetUnmappedPropertyNames())
{
expression.ForMember(property, opt => opt.Ignore());
}
return expression;
}
}
最后在 Application Start Handler 下的 Global.asax 类中
AutoMapperConfigurator.Configure();
参考
您可以从包管理器控制台下载它
