Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

c# - Metadata were not loaded using MetadataType

I've got a some problem/question about MetadataType. I've got DLL helper-project for data access from MS SQL Server using LinqToSQL. I've also need to add a metadata for a generated class ClientInfoView. I've done it following way:

using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;

namespace DataAPI.LINQToSQL
{
    [MetadataType(typeof(ClientInfoViewMetaData))]
    public partial class ClientInfoView
    {
        internal sealed class ClientInfoViewMetaData
        {
            [Category("Main Data"), DisplayName("Client ID")]
            public int ID { get; set; }

            [Category("Main Data"), DisplayName("Login")]
            public string Login { get; set; }

            ...
        }
    }
}

But when I checked the attributes in runtime, I've found that ClientInfoView hasn't got any attributes.

Can you please help me to find a mistake?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

because metadatatype is not for such porposes but you can use this method

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

and you can use like this

bool res = PropertyHasAttribute<ClientInfoView>("Login", typeof(DisplayAttribute))

this tell you that the class property login has or has not displayattribute , but if you need to findout attribute Value you can use Attribute.GetCustomAttribute method and cast it to your selected attribute like display attribute and read Name property by .Name :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...