Kamran Shahid
Kamran Shahid

Reputation: 4124

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

Upvotes: 0

Views: 1193

Answers (2)

Kamran Shahid
Kamran Shahid

Reputation: 4124

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

Upvotes: 0

Serge
Serge

Reputation: 43949

Adapt this testing code to your needs:

using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.IO;
using System.Linq;
using System.Reflection;


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

        [Required]
        public string appname { get; set; }
    }
    static void Main(string[] args)
    {

        GetClassAttributes(typeof(AuditLog ));
    }

    public static void GetClassAttributes(System.Type item)
    {
        var tableName=string.Empty;
        
        var tableAttr=item.GetCustomAttributes().FirstOrDefault() as TableAttribute;
        
        if (tableAttr != null) tableName = tableAttr.Name;
        Console.WriteLine("");
        Console.WriteLine("Table Name .... {0}", tableName);

        var properties = item.GetProperties();
        

        if (HasEFDataAnnotaion(properties))
        {
            Console.WriteLine("");
            Console.WriteLine("Found Data Annotations attributes at {0} ...", item.FullName);
            foreach (var property in properties)
            {
                var attributes = property.GetCustomAttributes(false);

                // Using reflection.  
                Attribute[] attrs = System.Attribute.GetCustomAttributes(property);
            

                // Displaying output.  
                foreach (Attribute attr in attrs)
                {

                    if (attr is KeyAttribute)
                    {
                        KeyAttribute a = (KeyAttribute)attr;
                        Console.WriteLine("attribute {0} on {1} ", a.ToString(), property.Name);
                    }

                    if (attr is ForeignKeyAttribute)
                    {
                        ForeignKeyAttribute a = (ForeignKeyAttribute)attr;
                        Console.WriteLine("attribute {0} on {1} ", a.ToString(), property.Name);
                    }

                    //if (attr is IndexAttribute)
                    //{
                    //  IndexAttribute a = (IndexAttribute)attr;
                    //  Console.WriteLine("attribute {0} on {1} ", a.GetType().FullName + a.ToString(), property.Name);
                    //}

                    if (attr is RequiredAttribute)
                    {
                        RequiredAttribute a = (RequiredAttribute)attr;
                        Console.WriteLine("attribute {0} on {1} ", a.ToString(), property.Name);
                    }

                    if (attr is TimestampAttribute)
                    {
                        TimestampAttribute a = (TimestampAttribute)attr;
                        Console.WriteLine("attribute {0} on {1} ", a.ToString(), property.Name);
                    }

                    if (attr is ConcurrencyCheckAttribute)
                    {
                        ConcurrencyCheckAttribute a = (ConcurrencyCheckAttribute)attr;
                        Console.WriteLine("attribute {0} on {1} ", a.ToString(), property.Name);
                    }

                    if (attr is MinLengthAttribute)
                    {
                        MinLengthAttribute a = (MinLengthAttribute)attr;
                        Console.WriteLine("attribute {0} on {1} ", a.ToString(), property.Name);
                    }

                    if (attr is MaxLengthAttribute)
                    {
                        MaxLengthAttribute a = (MaxLengthAttribute)attr;
                        Console.WriteLine("attribute {0} on {1} ", a.ToString(), property.Name);
                    }

                    if (attr is StringLengthAttribute)
                    {
                        StringLengthAttribute a = (StringLengthAttribute)attr;
                        Console.WriteLine("attribute {0} on {1} ", a.ToString(), property.Name);
                    }

                    if (attr is TableAttribute)
                    {
                        TableAttribute a = (TableAttribute)attr;
                        Console.WriteLine("attribute {0} on {1} ", a.ToString(), property.Name);
                    }

                    if (attr is ColumnAttribute)
                    {
                        ColumnAttribute a = (ColumnAttribute)attr;
                        Console.WriteLine("attribute {0} on {1} ", a.ToString(), property.Name);
                    }

                    if (attr is DatabaseGeneratedAttribute)
                    {
                        DatabaseGeneratedAttribute a = (DatabaseGeneratedAttribute)attr;
                        Console.WriteLine("attribute {0} on {1} ", a.ToString(), property.Name);
                    }

                    if (attr is ComplexTypeAttribute)
                    {
                        ComplexTypeAttribute a = (ComplexTypeAttribute)attr;
                        Console.WriteLine("attribute {0} on {1} ", a.ToString(), property.Name);
                    }
                }
            }
        }
    }

}
    private static bool HasEFDataAnnotaion(PropertyInfo[] properties)
    {
        return properties.ToList().Any((property) =>
        {
            var attributes = property.GetCustomAttributes(false);
            Attribute[] attrs = System.Attribute.GetCustomAttributes(property);
            return attrs.Any((attr) =>
            {
                return attr is KeyAttribute || attr is ForeignKeyAttribute || attr is RequiredAttribute || attr is TimestampAttribute //||  attr is IndexAttribute 
                || attr is ConcurrencyCheckAttribute || attr is MinLengthAttribute || attr is MinLengthAttribute
                || attr is MaxLengthAttribute || attr is StringLengthAttribute || attr is TableAttribute || attr is ColumnAttribute
                || attr is DatabaseGeneratedAttribute || attr is ComplexTypeAttribute;
            });
        });
    }
    

UPDATE

if you need a key property value change the beginning of my code to this:

static void Main(string[] args)
    {
        var auditLog = new AuditLog {auditlog_id=1, appname="first log"};

     GetObjectAttributes(auditLog);
    }
    public static void GetObjectAttributes(object item)
    {
        
      var itemType= item.GetType()  ;
    
        var tableName=string.Empty;
        
        var tableAttr=itemType.GetCustomAttributes().FirstOrDefault() as TableAttribute;

        if (tableAttr != null) tableName = tableAttr.Name;
        Console.WriteLine("");
        Console.WriteLine("Table Name .... {0}", tableName);

        var properties = itemType.GetProperties();


        if (HasEFDataAnnotaion(properties))
        {
            Console.WriteLine("");
            Console.WriteLine("Found Data Annotations attributes at {0} ...", tableName);
            foreach (var property in properties)
            {
                var attributes = property.GetCustomAttributes(false);

                // Using reflection.  
                Attribute[] attrs = System.Attribute.GetCustomAttributes(property);
        

                // Displaying output.  
                foreach (Attribute attr in attrs)
                {

                    if (attr is KeyAttribute)
                    {
                        KeyAttribute a = (KeyAttribute)attr;
                        Console.WriteLine("attribute {0} on {1} ", a.ToString(), property.Name);
                        Console.WriteLine("property value on {1} is {0}  ", property.GetValue(item ), property.Name);
                    }
......Continue code above if you need another attributes

Upvotes: 2

Related Questions