Reputation: 2914
Is it possible to map AddToClientCommand
to 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; }
}
to achieve the following result:
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);
Upvotes: 0
Views: 383
Reputation: 655
AutoMapper : As my understanding, it is impossible to map AddToClientCommand
to List<AddToClient>
. because the AotuMapper provide 2 ways for mapping such as following...
For Example: We have 2 classes like Employee and User
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. Creates the map and all fields are copied if properties are same
Mapper.CreateMap<Employee, User>();
//2. If properties are different we need to map fields of employee to that of user as below.
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);
// But your requirement will be fullfill through 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();
Upvotes: 1
Reputation: 211
No need to use AutoMapper here. You can do what you want with a Linq query
var expected = command.AccountIds.Select(id => new AddToClient { AccountId = id, ClientId = command.ClientId }).ToList();
Upvotes: 0