/// <summary> /// 根据主键查询 /// </summary> /// <typeparam name="T">T</typeparam> /// <param name="obj">对象</param> /// <param name="tid">主键值</param> /// <returns></returns> public T Get <T>(object obj, int tid) where T : new() { //从缓存中读取该主键值的数据是否存在() var tp = obj.GetType(); string key = tp.ToString() + "." + tid; MyCache.Caching cache = new MyCache.Caching(); T v = new T(); if (cache.IsCache(key)) { v = (T)cache.Get(key); } else { string WrongMessage = null; string SelectSql = CreateSelectSQL(typeof(T), obj, "this.tid=" + tid, 0); var dt = _DBLInit.GetDataTable(SelectSql, out WrongMessage); if (WrongMessage == null) { List <T> myList = new List <T>(dt.Rows.Count); int i = 0; foreach (DataRow dr in dt.Rows) { object objClass = Activator.CreateInstance(typeof(T), null); myList.Add((T)DataPacking(typeof(T), objClass, dr)); i++; } if (myList.Count == 1) { v = myList[0]; cache.Add(key, v); } } else { //ClassCommon.LogError(String.Format("{0}|{1}", SelectSql, WrongMessage)); } } return(v); }
/// <summary> /// 生成查询语句 /// </summary> /// <param name="tp">实例的类型</param> /// <param name="obj">实例</param> /// <param name="Qual">查询条件</param> /// <param name="top">返回的记录数</param> /// <returns></returns> public string CreateSelectSQL(Type tp, object obj, string Qual, int top) { //缓存SQL语句 string key = tp.ToString(); string keyTableName = tp.ToString() + "TableName"; MyCache.Caching cache = new MyCache.Caching(); string sql = "select "; string _TableName = this._TableName; if (!cache.IsCache(key)) { int tidflag = 0; string _PrimaryKey = ""; FieldInfo[] fis = tp.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); if (top > 0) { sql += String.Format(" top ({0}) ", top); } for (int i = 0; i < fis.Length; i++) { if (String.Compare(fis[i].Name, "_TableName", false) == 0) { //_TableName = fis[i].GetValue(obj).ToString(); } else if (String.Compare(fis[i].Name, "_PrimaryKey", false) == 0) { _PrimaryKey = fis[i].GetValue(obj).ToString(); } else if (String.Compare(fis[i].Name, "returnDt", false) == 0) { } else if (String.Compare(fis[i].Name, "_DBLInit", false) != 0 && String.Compare(fis[i].Name, "_JoinList", false) != 0) { if (fis[i].Name == "tid") { if (tidflag == 0) { sql += String.Format("this.{0},", fis[i].Name); tidflag = 1; } } else { sql += String.Format("this.{0},", fis[i].Name); } } } sql = sql.Substring(0, sql.Length - 1); sql = sql.Replace("this", _TableName); sql += " FROM " + _TableName; cache.Add(key, sql); cache.Add(keyTableName, _TableName); } else { sql = cache.Get(key).ToString(); _TableName = cache.Get(keyTableName).ToString(); } if (string.IsNullOrEmpty(Qual)) { return(sql); } Qual = Qual.Replace("this", _TableName); sql += " WHERE " + Qual; return(sql); }