使用实体框架,如何访问外键列的显示名称?

2024-05-04

我有以下注释:

    [Display(Name = "NotImportant", ResourceType = typeof(MyResxFile))]
    public int? PhoneModel { get; set; } // this is the id
    [Display(Name = "Important", ResourceType = typeof(MyResxFile))]
    public virtual PhoneModel PhoneModel1 { get; set; } // this is the object

我使用以下方法来获取显示名称:

    PropertyInfo pi = SomeObject.GetProperties[0]; // short example
    columnName = ReflectionExtensions.GetDisplayName(pi);

它适用于所有列except该代码没有找到诸如 PhoneModel1 之类的列的自定义/显示属性,即使明显有一个属性也是如此。它适用于int?但我不需要标题id,我需要实际值的标头,该值位于 PhoneModel1 中。

    public static class ReflectionExtensions
    {

        public static T GetAttribute<T>(this MemberInfo member, bool isRequired)
            where T : Attribute
        {
            var attribute = member.GetCustomAttributes(typeof(T), false).SingleOrDefault();

            if (attribute == null && isRequired)
            {
                throw new ArgumentException(
                    string.Format(
                        CultureInfo.InvariantCulture,
                        "The {0} attribute must be defined on member {1}",
                        typeof(T).Name,
                        member.Name));
            }

            return (T)attribute;
        }

        public static string GetDisplayName(PropertyInfo memberInfo)
        {
            var displayAttribute = memberInfo.GetAttribute<DisplayAttribute>(false);

            if (displayAttribute != null)
            {
                ResourceManager resourceManager = new ResourceManager(displayAttribute.ResourceType);
                var entry = resourceManager.GetResourceSet(Thread.CurrentThread.CurrentUICulture, true, true)
                                           .OfType<DictionaryEntry>()
                                           .FirstOrDefault(p => p.Key.ToString() == displayAttribute.Name);

                return entry.Value.ToString();
            }
            else
            {
                var displayNameAttribute = memberInfo.GetAttribute<DisplayNameAttribute>(false);
                if (displayNameAttribute != null)
                {
                    return displayNameAttribute.DisplayName;
                }
                else
                {
                    return memberInfo.Name;
                }
            }
        }
    }

Your GetDisplayName扩展方法应该如下所示:

public static string GetDisplayName(this PropertyInfo pi)
{
    if (pi == null)
    {
        throw new ArgumentNullException(nameof(pi));
    }
    return pi.IsDefined(typeof(DisplayAttribute)) ? pi.GetCustomAttribute<DisplayAttribute>().GetName() : pi.Name;
}

并使用它:

PropertyInfo pi = SomeObject.GetProperties[0];
string columnName = pi.GetDisplayName();

请注意,如果该属性没有定义DisplayNameattribute 我们返回属性名称。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用实体框架,如何访问外键列的显示名称? 的相关文章

随机推荐