日期:2014-05-17 浏览次数:20837 次
//Expression是表达式,表达式格式为类成员,如test<类>(n => n.成员1,n.成员2) void test<T>(Expression...)
namespace GetFields { class Program { static void Main(string[] args) { string cmd = BuildQueryString<Book>(b => b.Id, b => b.Name); Console.WriteLine(cmd); Console.Read(); } public static string BuildQueryString<T>(params Expression<Func<T, object>>[] expressions) { string selectCommandText = BuildNonConditionQueryString(typeof(T)); List<String> fields = new List<string>(); foreach (var exp in expressions) { fields.Add(GetFieldName<T>(exp)); } if (fields.Count > 0) { string temp = String.Join(",", fields); selectCommandText = selectCommandText.Replace("*", temp); } return selectCommandText; } public static string GetFieldName<T>(Expression<Func<T, object>> expression) { MemberExpression memberExpression = null; if (expression.Body.NodeType == ExpressionType.Convert) { memberExpression = (MemberExpression)((UnaryExpression)expression.Body).Operand; } else if (expression.Body.NodeType == ExpressionType.MemberAccess) { memberExpression = (MemberExpression)expression.Body; } if (null == memberExpression) { throw new Exception("...."); } FieldNameAttribute fa = (FieldNameAttribute)Attribute.GetCustomAttribute(memberExpression.Member, typeof(FieldNameAttribute)); return fa.Name; } public static string BuildNonConditionQueryString(Type type) { TableNameAttribute ta = (TableNameAttribute)Attribute.GetCustomAttribute(type, typeof(TableNameAttribute)); if (null != ta) { StringBuilder sb = new StringBuilder(); sb.AppendFormat(" select * from {0} ", ta.Name); return sb.ToString(); } else { throw new Exception("....."); } } } [TableNameAttribute(Name = "tb_book")] public class Book { [FieldName(Name = "id", Key = true)] public string Id { get; set; } [FieldName(Name = "name")] public string Name { get; set; } [FieldName(Name = "author_id")] public string AuthorId { get; set; } } public class TableNameAttribute : Attribute { public string Name { get; set; } } public class FieldNameAttribute : Attribute { public FieldNameAttribute()