[英]Automapper: Map property of type X from source object to destination object with equivlanet properties to type X
不確定我用的是正確的措詞,因此希望示例足夠清楚。
我想做的事情對我來說似乎很基礎,所以我假設我缺少明顯的東西。
對於此示例,這兩個ForMember
映射很簡單,可以完成工作。 問題是對於更復雜的類,給定配置了任何中間映射,您如何簡單地將一個對象的屬性映射到整個目標?
我現在搜索了一段時間,最接近找到答案的位置在這里,但是ConvertUsing
語法對我不起作用(我使用的是Automapper 4.2.1)
以下是示例類:
public class UserRoleDto
{
public string Name { get; set; }
public string Description { get; set; }
}
public class DbRole
{
public Guid RoleId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
public class DbUserRole
{
public Guid UserId { get; set; }
public DbRole Role { get; set; }
}
這是我使用Automapper配置設置的測試用例(在LINQPad中進行測試,這就是最后一行最后的Dump()的作用)
var dbRole = new DbRole { RoleId = Guid.NewGuid(), Name = "Role Name", Description = "Role Description" };
var dbUserRole = new DbUserRole { UserId = Guid.NewGuid(), Role = dbRole };
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<DbRole, UserRoleDto>();
/* Works but verbose for a class with more than a few props */
cfg.CreateMap<DbUserRole, UserRoleDto>()
.ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Role.Name))
.ForMember(dest => dest.Description, opt => opt.MapFrom(src => src.Role.Description))
;
});
config.AssertConfigurationIsValid();
var mapper = config.CreateMapper();
var userRoleDto = mapper.Map<UserRoleDto>(dbUserRole).Dump();
傳入要映射的子對象怎么樣? 例如
cfg.CreateMap<DbRole, UserRoleDto>();
然后,不映射dbUserRole
,而是映射dbUserRole.Role
。
var userRoleDto = mapper.Map<UserRoleDto>(dbUserRole.Role);
這是另一個使用以下類的示例:
public class Person
{
public int person_id;
public int age;
public string name;
}
public class Address
{
public int address_id;
public string line1;
public string line2;
public string city;
public string state;
public string country;
public string zip;
}
public class PersonWithAddress
{
public int person_id;
public int age;
public string name;
public InnerAddress address;
}
public class InnerAddress
{
public string city;
public string state;
public string country;
}
使用以下測試用例:
var person = new Person { person_id = 100, age = 30, name = "Fred Flintstone" };
var address = new Address { address_id = 500, line1 = "123 Main St", line2 = "Suite 3", city = "Bedrock", state = "XY", country = "GBR", zip="90210" };
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Person, PersonWithAddress>();
cfg.CreateMap<Address, InnerAddress>();
});
var mapper = config.CreateMapper();
var person_with_address = mapper.Map<Person, PersonWithAddress>(person);
person_with_address.address = new InnerAddress();
mapper.Map<Address, InnerAddress>(address, person_with_address.address);
問候,
羅斯
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.