【问题标题】:use automapper to map models instead of foreach statement使用 automapper 映射模型而不是 foreach 语句
【发布时间】:2022-01-01 02:11:13
【问题描述】:
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>();

// 映射collection car中的所有对象并设置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);
    }   

如何利用 automapper 并用 automapper 替换整个 foreach(遍历整个汽车集合并设置 Owner 数据?

【问题讨论】:

标签: c# .net-core automapper


【解决方案1】:

首先,您应该将AutoMapper.Extensions.Microsoft.DependencyInjection NuGet 包添加到您的项目中。 之后创建一个名为AutoMapperProfiles 的类并从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>();
    }
}

然后在 Startup.cs 类上配置 AutoMapper。

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

您应该将IMapper 注入您的方法中。这里我使用了构造函数注入

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;
}

那你就可以这样使用了。

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

使用这种方法的好处是DI(依赖注入)

希望这会奏效。

【讨论】:

    猜你喜欢
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多