Automapper:如何将对象列表扁平化为单个对象

Automapper: how to flat a list of object into a single object

我从数据库中得到了这个实体

public class SettingsDb
{
    public int Id { get; set; }
    public string Section { get; set; }
    public string Name { get; set; }
    public string Value { get; set; }
}

意思是:

model/to class 就是

public class FtpSettings
{
    public bool Enabled { get; set; }
    public string Server { get; set; }
    public int Port { get; set; }
    public string Protocol { get; set; }
    public string SSLStartMode { get; set; }
    public string User { get; set; }
    public string Password { get; set; }
}

我必须将列表 IList 扁平化为单个 model/dto 对象 FtpSettings(假设它已经从 SQL 查询的部分中过滤)

我怎样才能做到这一点?

谢谢。

//your model
public class FtpSettings
{
    // tle IList that you want
    public IList<SettingsDb> flatIlist {get;set;}
}

或者您可以像这样直接在视图中添加 Ilist:

@model IList<SettingsDb>

在麻烦之后我做了以下事情。

一个转换器

public static class ConfigConverter<T> where T : class, new()
    {
        public static T GetSettings(IList<SettingsDb> settings)
        {
            var cfg = new MapperConfiguration(cfg =>
                cfg.CreateMap<IList<SettingsDb>, T>()
                .ConvertUsing<SettingsTypeConverter<T>>());

            var mapper = cfg.CreateMapper();

            var ftpSettings = mapper.Map<T>(settings);

            return ftpSettings;
        }
    }


    public class SettingsTypeConverter<T> : ITypeConverter<IList<SettingsDb>, T> where T : class, new()
    {

        public T Convert(IList<SettingsDb> source, T destination, ResolutionContext context)
        {

            var dto = new T();

            foreach (var setting in source)
            {
                foreach (var dtoProperty in dto.GetType().GetProperties())
                {
                    if (!setting.Name.Equals(dtoProperty.Name))
                    {
                        continue;
                    }

                    var tProp = dtoProperty.PropertyType;

                    if (!setting.Value.IsConvertibleTo(tProp))
                    {
                        //error

                        continue;
                    }

                    dtoProperty.SetValue(dto, setting.Value.To(tProp));

                }
            }

            return dto;


        }

可以用作

var ftpSettings = ConfigConverter<FtpSettings>.GetSettings(settingsDb);

必须通过Nuget安装AutoMapper和UniversalTypeConverter