Get information stored in an "attribute"

4

In the ORM I use, classes are mapped using Attributes . I need to retrieve the value stored in them. Ex.:

[Table("CADASTRO_CLIENTE")]
public class Cliente
{
    [Property("Id")]
    public int Id { get; set; }
}

Example usage (fictional - this is what I need to know)

var nomeTabela = Cliente.GetTableName();
//nomeTabela seria "CADASTRO_CLIENTE"

I'm using NHibernate with ActiveRecord.

    
asked by anonymous 11.12.2015 / 12:04

2 answers

4

You can do the following:

public static string GetTableName()
{
    TableAttribute myAttribute = (TableAttribute)Attribute.GetCustomAttribute(typeof(Cliente), typeof(TableAttribute));

    // versao pre C#6
    return myAttribute == null ? string.Empty: myAttribute.MyTableName;
    // ou entao
    // return myAttribute?.MyTableName ?? string.Empty;
}

(See here for an example on MSDN and see here a demo at dotNetFiddle).

    
11.12.2015 / 12:21
3

You can use the GetCustomAttributes method:

TableAttribute.GetCustomAttributes(typeof(Cliente), false).OfType<TableAttribute>().FirstOrDefault().Name;

Remember to treat any possible exceptions.

Reference: Attribute.GetCustomAttributes Method

    
11.12.2015 / 12:19