使用EntityFramework,如何访问外键列的DisplayName?

时间:2017-05-07 02:53:27

标签: asp.net-mvc entity-framework

我有以下注释:

    [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);

适用于所有列代码找不到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;
                }
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

试试这个:

var attribute =typeof(MyClass).GetProperty("Name").GetCustomAttributes(typeof(DisplayNameAttribute), true).Cast<DisplayNameAttribute>().Single();
string displayName = attribute.DisplayName; 

希望对您有所帮助。