Zerostar362
Zerostar362

Reputation: 18

C# Property data annotation

Is there a way to read, what annotations are bound to a property ?

I have code like this.

    [PrimaryKey]
    [Identity]
    public int Id { get; set; }
    [ForeignKey]
    public int OwnerId { get; set; }
    [ForeignKey]
    public int RegionId { get; set; }
    public string Name { get; set; } = null!;
    public double Price { get; set; }

and I want to know if the property has Id has and Annotation, if yes what type. Also can a property have more than one annotation ?

My reading code looks like this, there is no annotation included

var type = typeof(TValue);
        var properties = type.GetProperties();
        var name = type.Name;
        string[] propertySQLstring = new string[properties.Length];
        string[] valueSQLstring = new string[properties.Length];
        for (int i = 0; i < properties.Length; i++)
        {
            if (i + 1 == properties.Length)
            {
                propertySQLstring[i] = properties[i].Name;
                valueSQLstring[i] = properties[i].GetValue(value)?.GetType() != typeof(string) ? properties[i].GetValue(value)?.ToString() : $"'{properties[i].GetValue(value)}'";
            }
            else
            {
                propertySQLstring[i] = properties[i].Name + ",";
                valueSQLstring[i] = properties[i].GetValue(value)?.GetType() != typeof(string) ? properties[i].GetValue(value)?.ToString() + ',' : $"'{properties[i].GetValue(value)}', ";
            }
        }

Thanks in advance.

Upvotes: 0

Views: 1136

Answers (1)

Will Moffat
Will Moffat

Reputation: 169

Assuming you have a list of predefined attributes you want to support, you could use GetCustomAttributes() with the generic type for your attribute.

E.g.

        foreach (PropertyInfo property in typeof(T).GetProperties())
        {
            IEnumerable<PrimaryKeyAttribute> primaryKeyAttributes = property.GetCustomAttributes<PrimaryKeyAttribute>();
        }

If you just want to get all of them, you'd want to use GetCustomAttributes() without the generic type provided.

Upvotes: 1

Related Questions