[EF]如何取得ADO.NET Entity Framework中某Table的主鍵值設定

[EF]如何取得ADO.NET Entity Framework中某Table的主鍵值設定

由「如何取得ADO.NET實體資料模型中某Table的主鍵值設定」參考「Entity Framework 4 How to find the primary key?」可以取得EF某Table中PK屬性。

透過Extension Methods的方式,可以讓我們透過EntityObject去取得它的PK屬性,使用上比較直覺一點。如下,


MYEntityObj myE = new MYEntityObj();
PropertyInfo myEpk = myE.GetPK();

//或
PropertyInfo mypk2 = (new MYEntityObj()).GetPK();

EntityObject Extension Method Code如下,


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Reflection;
using System.Data.Objects.DataClasses;
//要加入 System.Data.Linq.dll 參考
using System.Data.Linq.Mapping;

namespace YourNameSpace
{
    public static class MyDBExtension
    {
        public static PropertyInfo GetPK(this EntityObject value)
        {
            PropertyInfo[] properties = value.GetType().GetProperties();
            foreach (PropertyInfo pI in properties)
            {
                System.Object[] attributes = pI.GetCustomAttributes(true);
                foreach (object attribute in attributes)
                {
                    if (attribute is EdmScalarPropertyAttribute)
                    {
                        if ((attribute as EdmScalarPropertyAttribute).EntityKeyProperty == true)
                            return pI;
                    }
                    else if (attribute is ColumnAttribute)
                    {

                        if ((attribute as ColumnAttribute).IsPrimaryKey == true)
                            return pI;
                    }
                }
            }
            return null;
        }
    }
}