S_a_k_Uの日記みたいなDB

~サクゥーと呼ばないで~

System.Data.Objects.DataClasses.EdmScalarPropertyAttributeの情報で主キーかどうかを判定

Entity Data Modelで、自動生成されたスキーマ(テーブル)に対応するクラスhogeのプロパティに設定されている、カスタム属性(System.Data.Objects.DataClasses.EdmScalarPropertyAttribute)のEntityKeyPropertyを取得して判定する。

using System;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            System.Type cinfo = typeof(hoge);
            // クラスcinfoのプロパティを取得
            foreach (System.Reflection.PropertyInfo pinfo in cinfo.GetProperties())
            {
                // プロパティpinfoのカスタム属性を取得
                foreach (Object att in pinfo.GetCustomAttributes(true))
                {
                    // System.Data.Objects.DataClasses.EdmScalarPropertyAttribute属性かどうかを判定
                    if (att is System.Data.Objects.DataClasses.EdmScalarPropertyAttribute)
                    {
                        // System.Data.Objects.DataClasses.EdmScalarPropertyAttribute属性のEntityKeyPropertyを判定
                        if (((System.Data.Objects.DataClasses.EdmScalarPropertyAttribute)att).EntityKeyProperty == true)
                        {
                            System.Console.WriteLine("クラス" + cinfo.Name + "のプロパティ" + pinfo.Name + "は、主キーです。");
                        }
                    }
                }
            }
            System.Console.ReadLine();
        }
    }
}


調べるクラスhogeのプロパティfugaはこんな感じのハズ。

/// <summary>
/// スキーマのプロパティ fugaにはコメントがありません。
/// </summary>
[global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
[global::System.Runtime.Serialization.DataMemberAttribute()]
[global::System.CodeDom.Compiler.GeneratedCode("System.Data.Entity.Design.EntityClassGenerator", "4.0.0.0")]
public string fuga
{
    get
    {
        return this._fuga;
    }
    set
    {
        this.OnfugaChanging(value);
        this.ReportPropertyChanging("fuga");
        this._fuga = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, false);
        this.ReportPropertyChanged("fuga");
        this.OnfugaChanged();
    }
}