0
public class Car
{
    public int Id {get;set;}        
    public string Name {get;set;}
    public Owner OwnerData {get;set}
}

public class Owner
{
    public int Id {get;set;}
    public string Name {get;set;}
    public string Phone {get;set;}
    public string CarName {get;set;}
}      

Owner ownerData = repository.Get<Owner>(id);
IEnumerable<Car> cars = repository.Get<Car>();

// map all objects in the collection cars and set OwnerData

    var data = new List<Car>();
    foreach(var car in cars) //replace this with automapper
    {
       car.OwnerData = new Owner
       {
          CarName = ownerData.CarName,
          Name = ownerData.Name,
          Phone = ownerData.Phone
       };

       data.Add(car);
    }   

How can I take advantage of automapper and replace whole foreach with automapper (iterate through whole cars collection and set Owner data?

user1765862
  • 13,635
  • 28
  • 115
  • 220
  • 1
    Does this answer your question? [Mapping Lists using Automapper](https://stackoverflow.com/questions/5589471/mapping-lists-using-automapper) – SᴇM Nov 22 '21 at 13:28

1 Answers1

-1

At first, you should add AutoMapper.Extensions.Microsoft.DependencyInjection NuGet package to your project. After that create a Class called AutoMapperProfiles and inherit it from the Profile.

public class AutoMapperProfiles : Profile
{
    /// <summary>
    /// Create mapping configuration from one type to another type
    /// </summary>
    public AutoMapperProfiles()
    {
        Car oCar = new Car();
        CreateMap<oCar.OwnerData, Owner>();
        CreateMap<Owner, oCar.OwnerData>();
    }
}

After that configure the AutoMapper on the Startup.cs class.

services.AddAutoMapper(typeof(AutoMapperProfiles).Assembly);

You should inject IMapper into your methods. Here I used constructor injection

private readonly IMapper _mapper;

/// <summary>
/// Inject Generic Repository and IMapper Service to the controller
/// </summary>
/// <param name="mapper"></param>
public YourConstructor(IMapper mapper)
{
    _mapper = mapper;
}

Then you can use it like this.

Car oCar = new Car();
var data = _mapper.Map<List<oCar.OwnerData>>(cars);

The advantage is using this method is DI (Dependency Injection)

Hope this will work.