TheKobra
TheKobra

Reputation: 911

Detecting attributes on a class to infer property?

I am not too familiar with reflection, however, would it be possible to implement a method that will return an object if that class has a property associated with a certain attribute?

I thought it might make this following implementation not being required

public interface IEntity
{
    object ID { get; }
}
public class Person : IEntity
{
    [Key]
    public int PersonID { get; }
    public string Name { get; set; }
    public int Age { get; set; }

    object IEntity.ID
    {
        get { return PersonID; }
    }
}

So instead of implementing 'IEntity' for every class, you can just do something like this:

public abstract class EntityBase
{
    public object ID { get { return FindPrimaryKey(); } }

    protected object FindPrimaryKey()
    {
        object key = null;
        try
        {
            //Reflection magic
        }
        catch (Exception) { }
        return key;
    }
}

This would just save some time instead of having to go through all code-first generated classes and implementing this small feature.

Upvotes: 1

Views: 103

Answers (1)

Mike Perrenoud
Mike Perrenoud

Reputation: 67898

Yes, that can definitely be done. Consider the following code:

protected object FindPrimaryKey()
{
    object key = null;
    var prop = this.GetType()
                   .GetProperties()
                   .Where(p => Attribute.IsDefined(p, typeof(Key)))
    if (prop != null) { key = prop.GetValue(this); }
    return key;
}

However, I would recommend caching that value. Add a private field for the key value:

object _keyValue;

and then set that:

protected void FindPrimaryKey()
{
    var prop = this.GetType()
                   .GetProperties()
                   .Where(p => Attribute.IsDefined(p, typeof(Key)))
    if (prop != null) { _keyValue = prop.GetValue(this); }
}

and then return that instead:

public object ID { get { return _keyValue; } }

Upvotes: 2

Related Questions