使用 Automapper 将一个类实例映射到另一个类的列表
Posted
技术标签:
【中文标题】使用 Automapper 将一个类实例映射到另一个类的列表【英文标题】:Map a class instance to a list of another class with Automapper 【发布时间】:2020-02-12 05:39:36 【问题描述】:是否可以将AddToClientCommand
映射到List<AddToClient>
?
public class AddToClientCommand : IRequest<AddToClientResponse>
public List<int> AccountIds get; set;
public int ClientId get; set;
public class AddToClient
public int AccountId get; set;
public int ClientId get; set;
达到以下效果:
var command = new AddToClientCommand
AccountIds = new List<int> 1, 2 ,
ClientId = 42
;
var result = // somehow automap with Automapper
var expected = new List<AddToClient>
new AddToClient AccountId = 1, ClientId = 42 ,
new AddToClient AccountId = 2, ClientId = 42
;
expected.Should().BeEquivalentTo(result);
【问题讨论】:
【参考方案1】:这里不需要使用 AutoMapper。 你可以用 Linq 查询做你想做的事
var expected = command.AccountIds.Select(id => new AddToClient AccountId = id, ClientId = command.ClientId ).ToList();
【讨论】:
【参考方案2】:AutoMapper : 据我了解,将AddToClientCommand
映射到List<AddToClient>
是不可能的。因为 AotuMapper 提供了 2 种映射方式,如下...
例如:我们有 Employee 和 User 等 2 个类
public class Employee
public int EmployeeId get; set;
public string EmployeeFName get; set;
public string EmployeeLName get; set;
public string Address get; set;
public string City get; set;
public string State get; set;
public string Zip get; set;
public DateTime? DateOfJoining get; set;
public class User
public int Userid get; set;
public string UserFName get; set;
public string UserLName get; set;
public string Address get; set;
public string City get; set;
public string State get; set;
public string Zip get; set;
public DateTime? DateOfJoining get; set;
Employee objEmployee = new Employee
EmployeeId = 1001,
EmployeeFName = "Manish",
EmployeeLName = "Kumar",
Address = "JAIPUR",
City = "JAIPUR",
State = "RAJASTHAN",
Zip = "302004",
DateOfJoining = DateTime.Now,
;
//1.如果属性相同,则创建地图并复制所有字段
Mapper.CreateMap<Employee, User>();
//2.如果属性不同,我们需要将员工的字段映射到用户的字段,如下所示。
AutoMapper.Mapper.CreateMap<Employee, User>()
.ForMember(o => o.Userid, b => b.MapFrom(z => z.EmployeeId))
.ForMember(o => o.UserFName, b => b.MapFrom(z => z.EmployeeFName))
.ForMember(o => o.UserLName, b => b.MapFrom(z => z.EmployeeLName));
User objuser = Mapper.Map<Employee, User>(objEmployee);
// 但是您的要求将通过 Linq Query 来满足...
AddToClientCommand addCommand = new AddToClientCommand
AccountIds = new List<int> 1, 2 ,
ClientId = 42
;
List<AddToClient> addClientList = addCommand.AccountIds.Select(item => new AddToClient AccountId = item, ClientId = addCommand.ClientId ).ToList();
输出:
【讨论】:
谢谢,我知道可以用 LINQ 完成。我只是想知道Automapper
是否有可能以上是关于使用 Automapper 将一个类实例映射到另一个类的列表的主要内容,如果未能解决你的问题,请参考以下文章
ASP.NET Core 中的对象映射之 AutoMapper