首页 > 代码库 > 获取强类型检测的属性名

获取强类型检测的属性名

<style></style>

在使用EFCodefirst时,由于EF的局限性,不得不让我们去拼一些查询语句,如下:

string sql = string.Format("select ID,[Name] from User");
。。。
但是这样的代码是没有类型检测的,比如某天项目经理强迫症犯了,将User实体类的“ID”改成UserID,那么程序就会报查询异常错误。那怎么做到强类型检测呢?
方法(推荐):
using System.Linq.Expressions 
/*************************************************************************
*GUID0caf04be-5cbd-42fd-8294-fdffc5f9f52e 
*AuthorHollson@qq.com
*Code Caption:
***************************************************************************/
namespace System
{
    /// <summary>
    /// 获取强类型检测的属性名
    /// </summary>
    public static class Strong
    {
        public static string PropertyName<T>(Expression<Func<T, object>> exp)
        {
            string result = string.Empty;
            if (exp.Body is UnaryExpression)
            {
                result = ((MemberExpression)((UnaryExpression)exp.Body).Operand).Member.Name;
            }
            else if (exp.Body is MemberExpression)
            {
                result = ((MemberExpression)exp.Body).Member.Name;
            }
            else if (exp.Body is ParameterExpression)
            {
                result = ((ParameterExpression)exp.Body).Type.Name;
            }
            return result;
        }
    }
}
 调用:(现在不管你谁怎么修改实体,我都不用再去打理它了)
           string id=Strong.PropertyName<User>(x=>x.UserID);

           string name=Strong.PropertyName<User>(x=>x.Name);

           string sqls = string.Format("select {0},{1} from User",id,name);

 

 
方法二:该方法就有点笨拙了,不过也不失为一种坚决方案。
namespace System
{
    public static class SystemExtend
    {
        /// <summary>
        ///获取强类型检测的属性名称
        /// </summary>
        /// <param name="t">对象类型</param>
        /// <param name="propertyName">属性名称</param>
        /// <returns>强类型检测的属性名称</returns>
        public static string StrongProperty(this Type t, string propertyName)
        {
            if (t.IsClass)
            {
                try
                {
                    return t.GetProperty(propertyName).Name;
                }
                catch (Exception)
                {
                    throw new Exception(string.Format("请检查\"{0}\"是否为类\"{1}\"的有效属性"propertyNamet.Name));
                }
            }
            else
            {
                throw new Exception(string.Format("\"{0}\"不是有效的类!"t.Name));
            }
        }
    }
调用:
    Type t=typeof(User);
    string sql = string.Format("select 0,1 from User",t.StrongProperty("UserID"),t.StrongProperty("Name"));
现在修改代码,再也不用怕到投鼠忌器了!!!