/// <summary> /// 立即执行删除记录语句 /// </summary> /// <typeparam name="TModel">模型名称</typeparam> /// <returns>将返回一个操作接口,此接口会有一个Where方法和Go方法,Where表示要添加条件,Go则表示立即执行语句。</returns> ///<example>session.Delete().Where(u => u.ID == "5");</example> public IOperatorWhere <TModel> Delete <TModel>() where TModel : DbObject { var tableName = DbMetaDataManager.GetTableName(typeof(TModel)); string template = string.Format("DELETE From {0} Where 1=1", tableName); return(new OperatorWhereObject <TModel>(Provider, template, null)); }
/// <summary> /// 更新DataSet,如果DataSet中有行添加、删除或数据更新则按每条数据执行相应的SQL语句。 /// 必须对已用Query对象查询出来的DataSet或者在Command中指定TableName。 /// </summary> /// <param name="ds"></param> public void UpdateDataSet <T>(DataSet ds, QueryConditional <T> whereObject = null) where T : DbObject { var table = ds.Tables[0]; string tableName = string.Empty; if (whereObject != null) { tableName = DbMetaDataManager.GetTableName(typeof(T)); } else { tableName = table.TableName; } if (string.IsNullOrEmpty(tableName)) { throw new InvalidOperationException("表名不能为空!"); } string whereSQL = null; if (whereObject != null) { whereSQL = whereObject.ToString(); } Provider.UpdateDataSet(ds, whereSQL); }
/// <summary> /// 得到主键的列名和参数名 /// </summary> static private string GetKeysParamNames(Type tmodel, string paramPrefix) { var keys = DbMetaDataManager.GetKeys(tmodel); var values = String.Join(" And ", keys.Select(f => f + "=" + paramPrefix + f) ); return(values); }
/// <summary> /// 立即返回数据DataSet /// </summary> /// <returns>数据DataSet</returns> public DataSet ToDataSet() { var tableName = DbMetaDataManager.GetTableName(ModelType); return(Provider.Query(new Command(this.ToString()) { TableName = tableName })); }
/// <summary> /// 得到除主键和自增列外的列名与值 /// </summary> static private string GetParamNameAndValues(Type tmodel, string paramPrefix) { var fs = DbMetaDataManager.GetMetaDatas(tmodel) .Where(md => !md.IDentity && !md.IsKey); var values = String.Join(",", fs.Select(f => f.FieldName + "=" + paramPrefix + f.FieldName) ); return(values); }
/// <summary> /// 得到除自增列以外所有列的列名 /// </summary> static private string GetFields(Type tmodel) { var fs = DbMetaDataManager.GetMetaDatas(tmodel) .Where(md => !md.IDentity); var fields = String.Join(",", fs.Select(f => f.FieldName) ); return(fields); }
public static string GetMetaFieldName <T>(int tabIdx, string propertyName) { string fieldName = string.Empty; var field = DbMetaDataManager.GetFieldName(typeof(T), propertyName); if (field != null) { fieldName = string.Format("T{0}.{1}", tabIdx, field); } return(fieldName); }
/// <summary> /// 创建查询对象 /// </summary> /// <returns>Query</returns> public SelectQuery <TModel> CreateQuery <TModel>() { object model = default(TModel); if (!_modelTypeCable.TryGetValue(typeof(TModel), out model)) { model = Activator.CreateInstance(typeof(TModel)); _modelTypeCable.TryAdd(typeof(TModel), model); DbMetaDataManager.GetMetaDatas(typeof(TModel)); } return(new SelectQuery <TModel>(Provider)); }
protected override Expression VisitMember(MemberExpression node) { var fieldName = DbMetaDataManager.GetFieldName(node.Member.DeclaringType, node.Member.Name); string tn = string.Empty; if (Ass.TryGetValue(node.Member.DeclaringType, out tn)) { sb.Append(tn); sb.Append("."); } sb.Append(fieldName); return(node); }
/// <summary> /// 立即执行更新语句 /// </summary> /// <typeparam name="TModel">模型名称</typeparam> /// <param name="objExp">更新对象表达式,表示要更新的列信息</param> /// <returns>将返回一个操作接口,此接口会有一个Where方法和Go方法,Where表示要添加条件,Go则表示立即执行语句。</returns> /// <example> session.Update(u => new AdminUser1 {ID = "5", NameA = "maxzhang"}).Where(p => p.Age > 5).Go</example> public IOperatorWhere <TModel> Update <TModel>(Expression <Func <TModel, object> > objExp) where TModel : DbObject { var tableName = DbMetaDataManager.GetTableName(typeof(TModel)); FieldsFormater format = new FieldsFormater(Provider); format.Visit(objExp); string paramterNameAndValues = string.Join(",", format.Parameters.Select(kv => kv.Key + "=" + kv.Value.Name)); string template = string.Format("Update {0} SET {1} Where 1=1", tableName, paramterNameAndValues); var ps = format.Parameters.Values.Where(p => p.IsMethodType == false).ToList(); return(new OperatorWhereObject <TModel>(Provider, template, ps)); }
/// <summary> /// 将所有用到的物理模型类型对象加载到缓存中。 /// </summary> /// <param name="dbtypes"></param> protected void LoadObjects(Type[] dbtypes) { foreach (var type in dbtypes) { object model = null; if (!DbSession._modelTypeCable.TryGetValue(type, out model)) { model = Activator.CreateInstance(type); DbSession._modelTypeCable.TryAdd(type, model); DbMetaDataManager.GetMetaDatas(type); } } }
/// <summary> /// 立即执行插入语句 /// </summary> /// <typeparam name="TModel">模型名称</typeparam> /// <param name="objExp">插入对象表达式,表达要插入的列信息</param> /// <example> session.Insert(u => new AdminUser1 {ID = "5", NameA = "maxzhang"}).Where(p => p.Age > 5).Go;</example> public void Insert <TModel>(Expression <Func <TModel, object> > objExp) where TModel : DbObject { var tableName = DbMetaDataManager.GetTableName(typeof(TModel)); FieldsFormater format = new FieldsFormater(Provider); format.Visit(objExp); string fieldNames = string.Join(",", format.Parameters.Keys); string paramterNames = string.Join(",", format.Parameters.Values.Select(p => p.Name)); string template = string.Format("INSERT INTO {0}({1}) VALUES({2})", tableName, fieldNames, paramterNames); var ps = format.Parameters.Values.Where(p => p.IsMethodType == false).ToList(); var command = new Command(template, ps); Provider.Execute(command); }
/// <summary> /// 得到模型对象中可移除属性,列名 /// </summary> static private string GetRemoveAbleFieldName(Type tmodel) { var fs = DbMetaDataManager.GetMetaDatas(tmodel) .Where(md => md.RemoveAble); var fmd = fs.FirstOrDefault(); if (fmd == null) { throw new InvalidOperationException("不能在没有可移除类型的对象上进行些操作!"); } return(fmd.FieldName); }
/// <summary> /// 选择返回列,用于返回指定名称属性集合数据源 /// </summary> /// <typeparam name="TModel"></typeparam> /// <param name="query"></param> /// <param name="newObject"></param> /// <returns>查询构造器,一般使用Select语句后应该执行查询</returns> public static SelectQuery <TModel> Select <TModel>(this SelectQuery <TModel> query, Expression <Func <TModel, object> > newObject) { var fields = TranslateExtendtion.TranslateObject(newObject, query.Provider) .Split(',') .Select(f => GetMetaFieldName <TModel>(query.TableIndex, f)).ToList(); query.SqlBuilder.ClearFields(); var keys = DbMetaDataManager.GetKeys(typeof(TModel)).Select(k => GetMetaFieldName <TModel>(query.TableIndex, k)); var keyAndFields = keys.ToList(); keyAndFields.AddRange(fields); keyAndFields.ForEach(f => query.SqlBuilder.AddField(f)); return(query); }
/// <summary> /// 返回分页数据 /// </summary> /// <typeparam name="TModel"></typeparam> /// <param name="query"></param> /// <param name="pageIndex">第几页</param> /// <param name="pageSize">共几页</param> /// <returns>延时执行查询,在调用时</returns> public static IEnumerable <TModel> GetPager <TModel>(this SelectQuery <TModel> query, int pageIndex, int pageSize) { query.SqlBuilder.Clear(); query.SqlBuilder.IsFunction = true; var tableName = DbMetaDataManager.GetTableName(typeof(TModel)); string where = query.WhereCreater.ToString().Replace("Where 1=1 AND", ""); Regex regex = new Regex(@"[a-z|A-Z]+\w*\."); where = regex.Replace(where, @""); var key = DbMetaDataManager.GetKeys(typeof(TModel))[0]; query.SqlBuilder.FuncSQL = string.Format(@"EXEC sp_getdatapage {0}, {1}, '[{2}]', '{3}', '{4}'", pageIndex, pageSize, tableName, where, key); return(query.ToLazyList()); }
public SelectQuery(IDataProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } Init(provider); //MetaType metaType = MetaManager.GetMetaType(); var tableName = DbMetaDataManager.GetTableName(ModelType); var metaDataList = DbMetaDataManager.GetMetaDatas(ModelType); SqlBuilder.AddFromTable(tableName, TableIndex); foreach (var parameter in metaDataList) { SqlBuilder.AddField(string.Format("T{0}.{1}", TableIndex, parameter.FieldName)); } }
/// <summary> /// 访问成员 /// </summary> /// <param name="node"></param> /// <returns></returns> protected override Expression VisitMember(MemberExpression node) { if (node.Expression != null && (node.Expression.NodeType == ExpressionType.Parameter || node.Expression.NodeType == ExpressionType.MemberAccess) && isleft) { bool isAsName = false; var pse = node.Expression as ParameterExpression; if (pse != null && pse.Type == node.Member.DeclaringType) { if (!Ass.Keys.Contains(pse.Type)) { Ass.TryAdd(pse.Type, pse.Name); } isAsName = true; } string ts = string.Empty; if (!isAsName && !Ass.TryGetValue(node.Member.DeclaringType, out ts)) { GetParentMemberName(node.Expression); } var fieldName = DbMetaDataManager.GetFieldName(node.Member.DeclaringType, node.Member.Name); string tn = string.Empty; if (Ass.TryGetValue(node.Member.DeclaringType, out tn)) { sb.Append(tn); sb.Append("."); } sb.Append(fieldName); return(node); } else { LambdaExpression lambda = Expression.Lambda(node); var fn = lambda.Compile(); this.Visit(Expression.Constant(fn.DynamicInvoke(null), node.Type)); } return(node); }
protected override MemberAssignment VisitMemberAssignment(MemberAssignment node) { string propertyName = node.Member.Name; string fieldName = DbMetaDataManager.GetFieldName(node.Member.DeclaringType, propertyName); if (node.Expression.NodeType == ExpressionType.Call) { VisitMethodCall((MethodCallExpression)node.Expression, fieldName); } else if (node.Expression.NodeType == ExpressionType.Convert) { var ue = node.Expression as UnaryExpression; var call = ue.Operand as MethodCallExpression; if (call != null) { this.VisitMethodCall(call, fieldName); } else { this.MyVisitMember(ue.Operand as MemberExpression, fieldName); } } else { parameters.Add(fieldName, new Parameter(ParamPrefix + fieldName, null)); var constant = node.Expression as ConstantExpression; if (constant != null) { VisitConstant(constant, fieldName); } else { LambdaExpression lambda = Expression.Lambda(node.Expression); var fn = lambda.Compile(); VisitConstant(Expression.Constant(fn.DynamicInvoke(null), node.Expression.Type), fieldName); } } return(node); }
/// <summary> /// IDataReader to model object for the 'T'. /// 泛型方法:将一个实现IDataReader接口的对象的所有属性通过反射, /// 把属性Copy到有相同字段的实体对象中. /// </summary> /// <param name="T">实体类名(Model object name)</param> /// <param name="reader">IDataReader接口实例对象(Object is type of IDataReader)</param> /// <returns>Model object for the 'T'.</returns> public static T ToEntity <T>(this IDataReader reader) { PropertyInfo[] propertys = null; T entity = Activator.CreateInstance <T>(); propertys = new PropertyInfo[reader.FieldCount]; for (int i = 0; i < reader.FieldCount; i++) { string dbName = reader.GetName(i); string propertyName = DbMetaDataManager.GetPropertyName(typeof(T), dbName); if (string.IsNullOrEmpty(propertyName)) { continue; } propertys[i] = typeof(T).GetProperty(propertyName); if (propertys[i] != null && !reader.IsDBNull(i)) { try { object val = reader[i]; if (!IsNullableType(propertys[i].PropertyType)) { val = Convert.ChangeType(val, propertys[i].PropertyType); } if (IsBooleanType(propertys[i].PropertyType)) { val = Convert.ToBoolean(val); } propertys[i].SetValue(entity, val, null); } catch (Exception exxxx) { } } } return(entity); }
/// <summary> /// 得到表名 /// </summary> static private string GetTableName(Type tmodel) { var tableName = DbMetaDataManager.GetTableName(tmodel); return(tableName); }
/// <summary> /// 访问常量 /// </summary> /// <param name="c"></param> /// <returns></returns> protected override Expression VisitConstant(ConstantExpression c) { IQueryable q = c.Value as IQueryable; if (q != null) { var tableName = DbMetaDataManager.GetTableName(q.ElementType); sb.Append(tableName); sb.Append(" "); if (Ass.Keys.Count > 0) { sb.Append(Ass[q.ElementType]); } else { sb.Append("T"); } } else if (c.Value == null) { sb.Append("NULL"); } else { switch (Type.GetTypeCode(c.Value.GetType())) { case TypeCode.Boolean: sb.Append(((bool)c.Value) ? 1 : 0); break; case TypeCode.DateTime: string dtfs = "'{0}'"; if (!string.IsNullOrEmpty(Provider.DateTimeFlagString)) { dtfs = Provider.DateTimeFlagString; } sb.AppendFormat(dtfs, c.Value); break; case TypeCode.String: sb.Append("'"); sb.Append(c.Value); sb.Append("'"); break; case TypeCode.Object: var qeq = c.Value as QueryConditional; if (qeq != null) { sb.Append(qeq.ToString()); } else if (c.Type.IsArray) // { var array = c.Value as Array; if (array == null || array.Length == 0) { throw new InvalidOperationException(string.Format("语句中的数组数据不能为空值。", c.Value)); } object elementOne = array.GetValue(0); Type elementType = elementOne.GetType(); string format = "{0}"; if (elementType == typeof(string)) { format = "'{0}'"; } StringBuilder value = new StringBuilder(); value.Append("("); for (int i = 0; i < array.Length; i++) { value.AppendFormat(format, array.GetValue(i)); if (i != array.Length - 1) { value.Append(","); } } value.Append(")"); sb.Append(value.ToString()); } else { throw new NotSupportedException(string.Format("The constant for '{0}' is not supported", c.Value)); } break; default: sb.Append(c.Value); break; } } return(c); }