Home > OS >  Automapper: how to flat a list of object into a single object
Automapper: how to flat a list of object into a single object

Time:10-15

I have this entity from the database

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

It means:

  • Section: the main section of settings (e.g., FTP)
  • Name: name of the property (e.g., Enabled, Server etc.)
  • Value: value of the property (e.g. true, "www.server.it" etc)

The model/to class it is

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

I have to flat the list IList to a single model/dto object FtpSettings (supposing it is already filtered from the section from SQL query)

How can I achieve this?

Thank you.

CodePudding user response:

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

Or you can just add your Ilist directly in your View like this:

@model IList<SettingsDb>

CodePudding user response:

after troubling I did the following.

A converter

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;


        }

It can be used as

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

It must be installed AutoMapper and UniversalTypeConverter by Nuget

  • Related