码迷,mamicode.com
首页 > 其他好文 > 详细

获取强类型检测的属性名

时间:2014-06-20 21:19:08      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:style   class   code   ext   color   com   

在使用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"));

现在修改代码,再也不用怕到投鼠忌器了!!!

 

获取强类型检测的属性名,布布扣,bubuko.com

获取强类型检测的属性名

标签:style   class   code   ext   color   com   

原文地址:http://www.cnblogs.com/Hollson/p/3796013.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!