jeudi 19 juillet 2018

Auto Column Mapping Using Reflection and expression c#

is that possible to automate these mappings with reflection?

i have a simple column mapping :

var columnsMap = new Dictionary<string, Expression<Func<Industry, object>>>
    {
        ["id"] = v => v.Id,
        ["name"] = v => v.Name,
        ["isActive"] = v => v.IsActive
    };

i want to generate these mappings in a extension class:

public Dictionary<string, Expression<Func<T, object>>> GenerateMapper()
{
    var mapper = new Dictionary<string, Expression<Func<T, object>>>();
    foreach (var item in typeof(T).GetProperties())
    {
        // get dictionary key ======> its OK
        var name = Char.ToLowerInvariant(item.Name[0]) + item.Name.Substring(1); //camel-case name

        // get expression    =======> this is the problem
        Expression<Func<T, object>> exp = v => v.GetType().GetProperty(item.Name); ;

        // add to mapper object
        mapper.Add(name, exp);
    }

    return mapper;
}

i don't know is that possible to get my expression dynamically in run-time?





Aucun commentaire:

Enregistrer un commentaire