Get information stored in an "attribute"

Asked

Viewed 55 times

4

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

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

Example of use (fictitious - that’s what I need to know)

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

I’m using Nhibernate with Activerecord.

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

(Behold here an example in MSDN and see here a demonstration on dotNetFiddle).

3

You can use the Getcustomattributes method:

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

Remember to treat possible exceptions.

Reference: Attribute.Getcustomattributes Method

  • Good! Thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.