如何从我们在 C# 中使用的对象中获取 TableName 和 Key 字段值

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

我有一个像 类 这样的追随者,我将其用作我的 table 之一的 entity framework 核心的模型。 保存后我将对象传递给某种缓存工作。 如何获取表名和标记为键的字段的值(我使用单个字段作为键)

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

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

表名来自 System.ComponentModel.DataAnnotations.Schema 密钥来自 System.ComponentModel.DataAnnotations

我使用过自己的自定义属性,但这里想检查是否有某种内置方法可以访问这些值。 我必须传递对象并获取 table 键的名称和值

根据您的需要调整此测试代码:

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

更新

如果您需要键 属性 值,请将我的代码开头更改为:

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

非常感谢谢尔盖。 以下是我目前的解决方案

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