简体   繁体   中英

Mark properties of class for reflection in C#

Hi i got this simple DTO Class

public class Clientes_mdl
{        
    public int ID_Cliente { get; set; }
    public string RazonSocial { get; set; }        

    public Enumerador_mdl CondicionIva { get; set; }
    public Nullable<Enumerador_mdl> Transporte { get; set; }
    public IEnumerable<Direcciones_view> Direcciones { get; set; }
}       

ID_Cliente and RazonSocial a data properties. Transporte and Direcciones are navigation properties to other classes.

And I use this reflection code, to get class properties names:

protected void base_UpdateCommand(IDbCommand myCommand, TEntity entity, string sWhere)
{
    var properties = (typeof(TEntity)).GetProperties().ToList();

    foreach (var prop in properties)
    {
        if (prop.Name.ToUpper() != sKeyField.ToUpper()
        {
            sProps = sProps + prop.Name + "=@" + prop.Name + ", ";                    
        }
    }
}

Now I need a way to ignore navigation properties, and get only data properties names of the class (ID_Cliente and RazonSocial). Is there any decorators I can use to do that?

Thank you!

you could check if it is a class something like:

        var properties = typeof(Clientes_mdl).GetProperties();

        var propertyNames = properties
            .Where(x => x.PropertyType == typeof(string) ||
                        !x.PropertyType.IsClass ||
                        !typeof(IEnumerable).IsAssignableFrom(x.PropertyType)
            )
            .Select(x=>$"{x.Name} =@ {x.Name}")
            .ToArray();

        var propertyNameString = string.Join(",", propertyNames);

and if you wanted to leave the lists in there you could remove !typeof(IEnumerable).IsAssignableFrom(x.PropertyType)

Got it thanks to your suggestions:

public class Clientes_mdl
{        
    public int ID_Cliente { get; set; }
    public string RazonSocial { get; set; }        

    [KeyAttribute]
    public Enumerador_mdl CondicionIva { get; set; }
    [KeyAttribute]
    public Nullable<Enumerador_mdl> Transporte { get; set; }
    [KeyAttribute]
    public IEnumerable<Direcciones_view> Direcciones { get; set; }
}       

And the reflection code:

protected void base_UpdateCommand(IDbCommand myCommand, TEntity entity, string sWhere)
{
    var properties = (typeof(TEntity)).GetProperties().ToList();

    foreach (var prop in properties)
    {
        bool bIgnore = prop.GetCustomAttributes(true).Any(a => a is KeyAttribute);
        if (prop.Name.ToUpper() != sKeyField.ToUpper() && !bIgnore)
        {
            sProps = sProps + prop.Name + "=@" + prop.Name + ", ";                    
        }
    }
}

Thanks everyone!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM