GetCustomAttributes 和 [DatabaseGenerated(DatabaseGeneratedOption.Computed)]

GetCustomAttributes and [DatabaseGenerated(DatabaseGeneratedOption.Computed)]

如何在获取此类属性时跳过计算列?我可以为 NotMapped 做,但不确定 DatabaseGenerated(DatabaseGeneratedOption.Computed)?

  [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
        public bool AAUProcessing { get; set; }

跳过 NotMapped 和 Computred 列

var props = typeof(TK).GetProperties()
                    .Where(propertyInfo => !propertyInfo.GetCustomAttributes(typeof(NotMappedAttribute)).Any())
                    .ToArray();

只需将其转换为正确的类型 (DatabaseGeneratedAttribute),您就可以检查它的任何您认为合适的属性。

以下示例将过滤掉计算属性和未映射属性:

void Main()
{
    var props = typeof(TK).GetProperties()
                    .Where(IsNotMapped)
                    .Where(IsNotComputedColumn)
                    .ToArray();

    foreach (var property in props)
    {
        Console.WriteLine(property.Name);
    }
}

static bool IsNotMapped(PropertyInfo propertyInfo)
{
    return !propertyInfo
        .GetCustomAttributes(typeof(NotMappedAttribute))
        .Any();
}

static bool IsNotComputedColumn(PropertyInfo propertyInfo)
{
    return !propertyInfo
        .GetCustomAttributes(typeof(DatabaseGeneratedAttribute))
        .Cast<DatabaseGeneratedAttribute>()
        .Any(a => a.DatabaseGeneratedOption == DatabaseGeneratedOption.Computed);
}

public class TK
{
    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public bool IsComputed { get; set; }

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public bool IsIdentity { get; set; }

    [NotMapped]
    public bool NotMapped { get; set; }

    public bool StandardColumn { get; set; }
}

输出为

IsIdentity
StandardColumn