<string>

问题描述 投票:0回答:1
我有两种类型。一种是实体,一种是模型。该实体有一个名为

Items

 的属性,它是一个字符串。该模型有一个属性,也称为 
Items
,但它是字符串的 
List<string>

我正在使用 AutoMapper 来映射它 - 像这样:

CreateMap<Model, Entity>() .ForMember(dest => dest.Items, opt => opt.ConvertUsing<List<string>>(new ListToStringValueConverter()));
这是我的

ListToStringValueConverter

public class ListToStringValueConverter : IValueConverter<List<string>, string> { public string Convert(List<string> source, ResolutionContext context) { if (source != null) return string.Join(",", source); return string.Empty; } }
但是,当为模型中的实体完成映射时

entity = _mapper.Map<Entity>(model);
我得到 

entity.Items

 的值为

System.Collections.Generic.List`1[System.String]
为什么我的转换器没有将 ["1","2"] 转换为 "1,2" 而是


System.Collections.Generic.List

1[系统.字符串]`?

我错过了什么或做错了什么?

c# asp.net automapper
1个回答
0
投票
试试这个:

var list = new List<string> { "1", "2" }; var model = new Model { Items = list }; var configuration = new MapperConfiguration(cfg => cfg.CreateMap<Model, Entity>() .ForMember(dest => dest.Items, opt => opt.MapFrom(src => string.Join(',', src.Items)))); Mapper mapper = new Mapper(configuration); Entity entity = mapper.Map<Model, Entity>(model); Console.WriteLine("Items: " + entity.Items);
    
© www.soinside.com 2019 - 2024. All rights reserved.