元数据类型和 Attribute.IsDefined

MetadataType and Attribute.IsDefined

我正在使用数据库优先方法,并且有一个 class SalesWallboard 映射到数据库 table。

SalesWallboard.cs:

namespace Wallboards.DAL.SchnellDb
{
    public partial class SalesWallboard
    {
        public int Id { get; set; }
        public string StaffName { get; set; }
        ...
    }
}

我为此创建了一个元数据类型 class 以应用自定义属性

SalesWallboardModel.cs

namespace Wallboards.DAL.SchnellDb
{
    [MetadataType (typeof(SalesWallboardModel))]
    public partial class SalesWallboard
    {

    }

    public class SalesWallboardModel
    {
        [UpdateFromEclipse]
        public string StaffName { get; set; }
        ...
    }
}

但在我的代码中,当我使用 Attribute.IsDefined 检查它时,它总是抛出错误。

代码

var salesWallboardColumns = typeof(SalesWallboard).GetProperties();
foreach (var column in salesWallboardColumns)
{
    if (Attribute.IsDefined(column, typeof(UpdateFromEclipse))) //returns false
    {
        ...
    }
}

我已经检查了 here 给出的答案。但是我不明白这个例子。 有人可以帮我简化一下吗?

感谢@elgonzo 和@thehennyy 的评论和反思纠正我的理解。

我找到了我要找的东西 here。但我不得不进行如下所示的一些修改。

我创建了一个方法PropertyHasAttribute

private static bool PropertyHasAttribute<T>(string propertyName, Type attributeType)
{
    MetadataTypeAttribute att = (MetadataTypeAttribute)Attribute.GetCustomAttribute(typeof(T), typeof(MetadataTypeAttribute));
    if (att != null)
    {
        foreach (var prop in GetType(att.MetadataClassType.UnderlyingSystemType.FullName).GetProperties())
        {
            if (propertyName.ToLower() == prop.Name.ToLower() && Attribute.IsDefined(prop, attributeType))
                return true;
        }
    }
    return false;
}

我也得到了 here 的帮助,因为我的类型在不同的程序集中。

方法GetType

public static Type GetType(string typeName)
{
    var type = Type.GetType(typeName);
    if (type != null) return type;
    foreach (var a in AppDomain.CurrentDomain.GetAssemblies())
    {
        type = a.GetType(typeName);
        if (type != null)
            return type;
    }
    return null;
}

然后像这样在我的代码中使用它

代码

var salesWallboardColumns = typeof(SalesWallboard).GetProperties();
foreach (var column in salesWallboardColumns)
{
    var columnName = column.Name;
    if (PropertyHasAttribute<SalesWallboard>(columnName, typeof(UpdateFromEclipse)))
    {
        ...
    }
}