首页 > 解决方案 > 使用 automapper asp.net core 将对象列表保存到表中

问题描述

这是我的 DTO

public class Part1
{
    public Part1()
    {
        Value = new List<ValueList>();
    }

    public int Id{ get; set; }
    public List<ValueList> Value { get; set; }
}
public class ValueList
{
    public int Value1 { get; set; }
    public string Value2 { get; set; }
    public string Value3 { get; set; }
}

这是我的表结构,我想使用自动映射器将上面的 dto 保存到下面的 dto

public class Part1
{
    public int Id{ get; set; }
    public int Value1 { get; set; }
    public string Value2 { get; set; }
    public string Value3 { get; set; }
}

标签: asp.net-coreautomapper

解决方案


您想知道如何在新模型中将列表映射到单个字符串吗?

您可以查看我的演示,在映射器配置文件中,定义要映射的三个值:

public class AutoMapping : Profile
{
    public AutoMapping()
    {
        CreateMap<Part1, Part1DTO>()    //Part1DTO is your below model
             .ForMember(x => x.Value1, m => m.MapFrom(src => src.Value[0].Value1))
             .ForMember(x => x.Value2, m => m.MapFrom(src => src.Value[0].Value2))
             .ForMember(x => x.Value3, m => m.MapFrom(src => src.Value[0].Value3));
    }
}

控制器:

public IActionResult Index()
    {
        Part1 part1= new Part1()
        {
            Id=1,
            Value=new List<ValueList> { new ValueList { Value1=1,Value2="b",Value3="c"} }
        };  //define old model 
        var result = _mapper.Map<Part1DTO>(part1);  // map to new
        return View(result);
    }

不要忘记在 ConfigureServices 中添加:

services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

结果:

在此处输入图像描述


推荐阅读