C# 如何使AutoMapper创建类的实例
我有以下源类型:C# 如何使AutoMapper创建类的实例,c#,.net,automapper,C#,.net,Automapper,我有以下源类型: public class Source { public string FirstName { get; set; } public string LastName { get; set; } public string Address1 { get; set; } public string Address2 { get; set; } public string City { get; set; } public string
public class Source
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
}
我有以下目的地类型:
public class Destination
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Address HomeAddress { get; set; }
}
public class Address
{
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string PostalCode { get; set; }
}
我创建了一个映射:
Mapper.CreateMap<Source, Destination>();
Mapper.CreateMap();
如何配置映射以使其创建Address实例并使用源属性ZipCode映射Address.PostalCode属性?使用AfterMap,您可以指定在AutoMaper完成映射后如何进一步映射实体
Mapper.CreateMap<Source, Destination>()
.AfterMap((src, dest) =>
{
dest.HomeAddress = new Address {PostalCode = src.ZipCode};
}
);
Mapper.CreateMap()
.AfterMap((src,dest)=>
{
dest.HomeAddress=新地址{PostalCode=src.ZipCode};
}
);
我试过这个。不起作用。表达式'dest=>Convert(dest.Address.PostalCode)'必须解析为顶级成员。此外,我不想将初始化放在构造函数中,因为我不想在实例化新目标时始终创建和地址,只有当我从源映射时,我才希望创建地址。@Dismissile,它失败是因为您正在解析为Convert(…)
而不是dest.Address.PostalCode
。另外,看看这里的例子:看起来您可能不需要包含空构造函数,只要这两个类都有默认构造函数。我输入的内容和你的一模一样,我得到了错误。@Dismisse,我搞砸了。您必须将顶级属性与MapFrom一起使用,但可以使用AfterMap。我更新了我的帖子。