Search code examples
c#.netentity-frameworkreflectionef-code-first

GetCustomAttributes and [DatabaseGenerated(DatabaseGeneratedOption.Computed)]


How do I skip computred columns when getting properties like this? I can do it for NotMapped, but not sure about DatabaseGenerated(DatabaseGeneratedOption.Computed)?

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

Skip NotMapped and Computred Columns

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

Solution

  • Just cast it to the correct type (DatabaseGeneratedAttribute) and you can inspect it for whatever properties you deem appropriate.

    The following example will filter out computed and not-mapped properties:

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

    The output is

    IsIdentity
    StandardColumn