Attribute.IsDefined doesn't see attributes applied with MetadataType class

后端 未结 4 623
旧巷少年郎
旧巷少年郎 2020-12-03 01:35

If I apply attributes to a partial class via the MetadataType attribute, those attributes are not found via Attribute.IsDefined(). Anyone know why, or what

4条回答
  •  悲&欢浪女
    2020-12-03 02:04

    Given the following classes:

    public partial class Person
    {
        public int PersonId { get; set; }
    }
    
    [MetadataType(typeof(PersonMetadata))]
    public partial class Person
    {
        public partial class PersonMetadata
        {
            [Key]
            public int PersonId { get; set; }
        }
    }
    

    I needed to get see if Key has been defined on a property for Person class. I then needed to get the value of the property. Using @AdamGrid answer, I modified the code like this to get it:

    private static object GetPrimaryKeyValue(TEntity entity)
    {
        MetadataTypeAttribute[] metadataTypes = typeof(TEntity).GetCustomAttributes(typeof(MetadataTypeAttribute), true).OfType().ToArray();
        MetadataTypeAttribute metadata = metadataTypes.FirstOrDefault();
        if (metadata == null)
        {
            ThrowNotFound();
        }
    
        PropertyInfo[] properties = metadata.MetadataClassType.GetProperties();
        PropertyInfo primaryKeyProperty =
            properties.SingleOrDefault(x => Attribute.GetCustomAttribute(x, typeof(KeyAttribute)) as KeyAttribute != null);
        if (primaryKeyProperty == null)
        {
            ThrowNotFound();
        }
    
        object primaryKeyValue = typeof(TEntity).GetProperties().Single(x => x.Name == primaryKeyProperty.Name).GetValue(entity);
    
        return primaryKeyValue;
    }
    
    private static void ThrowNotFound()
    {
        throw new InvalidOperationException
                ($"The type {typeof(TEntity)} does not have a property with attribute KeyAttribute to indicate the primary key. You must add that attribute to one property of the class.");
    }
    

提交回复
热议问题