Search code examples
c#.net-coresystem.componentmodel

How to get TableName and Key field value from an object we are using in C#


I have a following like classes which i am using as model for entity framework core for one of my table. After saving i am passing the object for some sort of caching work. How can i get the TableName and the value of the field which is marked as Key (i am using single field as Key)

[Table("audit_log")]
public class AuditLog
{
    [Key]
    public long auditlog_id { get; set; }

    [Required]
    public string appname { get; set; }        
}

TableName is from System.ComponentModel.DataAnnotations.Schema Key is from System.ComponentModel.DataAnnotations

I have worked with my own custom attributes but here wanted to check if there is some buildin way of accessing these values. I have to pass the object and get tablename and value of the key


Solution

  • Thanks a lot Serge. Following is my solution at the moment

    public static Tuple<bool, string, string> GetDataAnotationDetail<T>(T item) where T : class
            {
                Tuple<bool, string, string> result = null;
    
                var tableName = string.Empty;
                var tableAttr = item.GetType().GetCustomAttributes().FirstOrDefault() as TableAttribute;
    
                if (tableAttr != null)
                {
                    tableName = tableAttr.Name;
                }
    
                var properties = item.GetType().GetProperties();
                bool breakcondition = false;
                foreach (var property in properties)
                {
                    Attribute[] attrs = Attribute.GetCustomAttributes(property);
                    if (attrs != null)
                    {
                        foreach (Attribute attr in attrs)
                        {
    
                            if (attr is KeyAttribute)
                            {
                                var a = (KeyAttribute)attr;
                                var obj = property.GetValue(item, null);
                                result = Tuple.Create(true, tableName, Convert.ToString(obj));
                                breakcondition = true;
                                break;
                            }
    
                        }
                    }
                    if (breakcondition)
                    {
                        break;
                    }
                }
    
                return result;
            }