asp.net-core - 使用 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; }
}
解决方案
您想知道如何在新模型中将列表映射到单个字符串吗?
您可以查看我的演示,在映射器配置文件中,定义要映射的三个值:
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());
结果:
推荐阅读
- javascript - 来自输入表单的嵌套 JSON
- angular - ngx-data table如何在angualr -6的数据表中显示嵌套的json数据
- sql-server - 在多部分标识符之间弹跳无法绑定和不明确的列名
- scala - RDD take() 方法如何在内部工作?
- css - CSS 展示邮票效果在 IE 11 中不起作用
- javascript - onDataPointClick 功能不起作用 - react-native-chart-kit
- javascript - 查询字符串更改时更新反应组件
- java - 模拟 Instant.now() 而不在构造函数中使用时钟或没有时钟对象
- reactjs - 用于编辑数据的 React 组件
- javascript - 在 React.JS 中的映射函数中嵌套映射函数