public IDataReader ExecuteReader(string cmdText, CommandType cmdType, object parameter) { return(this.ExecuteReader(cmdText, cmdType, PublicHelper.BuildParams(this._dbContext, parameter))); }
public override TEntity Insert <TEntity>(TEntity entity, string table) { PublicHelper.CheckNull(entity); TypeDescriptor typeDescriptor = EntityTypeContainer.GetDescriptor(typeof(TEntity)); Dictionary <PropertyDescriptor, object> keyValueMap = PrimaryKeyHelper.CreateKeyValueMap(typeDescriptor); Dictionary <PropertyDescriptor, DbExpression> insertColumns = new Dictionary <PropertyDescriptor, DbExpression>(); List <PropertyDescriptor> outputColumns = new List <PropertyDescriptor>(); foreach (PropertyDescriptor propertyDescriptor in typeDescriptor.PropertyDescriptors) { if (propertyDescriptor.IsAutoIncrement || propertyDescriptor.IsTimestamp()) { outputColumns.Add(propertyDescriptor); continue; } if (propertyDescriptor.HasSequence()) { DbMethodCallExpression getNextValueForSequenceExp = PublicHelper.MakeNextValueForSequenceDbExpression(propertyDescriptor); insertColumns.Add(propertyDescriptor, getNextValueForSequenceExp); outputColumns.Add(propertyDescriptor); continue; } object val = propertyDescriptor.GetValue(entity); if (propertyDescriptor.IsPrimaryKey) { keyValueMap[propertyDescriptor] = val; } DbExpression valExp = DbExpression.Parameter(val, propertyDescriptor.PropertyType, propertyDescriptor.Column.DbType); insertColumns.Add(propertyDescriptor, valExp); } PropertyDescriptor nullValueKey = keyValueMap.Where(a => a.Value == null && !a.Key.IsAutoIncrement).Select(a => a.Key).FirstOrDefault(); if (nullValueKey != null) { /* 主键为空并且主键又不是自增列 */ throw new ChloeException(string.Format("The primary key '{0}' could not be null.", nullValueKey.Property.Name)); } DbTable dbTable = table == null ? typeDescriptor.Table : new DbTable(table, typeDescriptor.Table.Schema); DbInsertExpression insertExp = new DbInsertExpression(dbTable); foreach (var kv in insertColumns) { insertExp.InsertColumns.Add(kv.Key.Column, kv.Value); } if (outputColumns.Count == 0) { this.ExecuteNonQuery(insertExp); return(entity); } List <Action <TEntity, IDataReader> > mappers = new List <Action <TEntity, IDataReader> >(); IDbExpressionTranslator translator = this.DatabaseProvider.CreateDbExpressionTranslator(); List <DbParam> parameters; string sql = null; if (outputColumns.Count == 1 && outputColumns[0].IsAutoIncrement) { sql = translator.Translate(insertExp, out parameters); /* 自增 id 不能用 output inserted.Id 输出,因为如果表设置了触发器的话会报错 */ sql = string.Concat(sql, ";", this.GetSelectLastInsertIdClause()); mappers.Add(GetMapper <TEntity>(outputColumns[0], 0)); } else { foreach (PropertyDescriptor outputColumn in outputColumns) { mappers.Add(GetMapper <TEntity>(outputColumn, insertExp.Returns.Count)); insertExp.Returns.Add(outputColumn.Column); } sql = translator.Translate(insertExp, out parameters); } IDataReader dataReader = this.Session.ExecuteReader(sql, parameters.ToArray()); using (dataReader) { dataReader.Read(); foreach (var mapper in mappers) { mapper(entity, dataReader); } } return(entity); }
public override int Update <TEntity>(TEntity entity, string table) { PublicHelper.CheckNull(entity); TypeDescriptor typeDescriptor = EntityTypeContainer.GetDescriptor(typeof(TEntity)); PublicHelper.EnsureHasPrimaryKey(typeDescriptor); Dictionary <PropertyDescriptor, object> keyValueMap = PrimaryKeyHelper.CreateKeyValueMap(typeDescriptor); IEntityState entityState = this.TryGetTrackedEntityState(entity); Dictionary <PropertyDescriptor, DbExpression> updateColumns = new Dictionary <PropertyDescriptor, DbExpression>(); PropertyDescriptor timestampProperty = null; object timestampValue = null; foreach (PropertyDescriptor propertyDescriptor in typeDescriptor.PropertyDescriptors) { if (propertyDescriptor.IsPrimaryKey) { keyValueMap[propertyDescriptor] = propertyDescriptor.GetValue(entity); continue; } if (propertyDescriptor.IsAutoIncrement || propertyDescriptor.HasSequence()) { continue; } if (propertyDescriptor.IsTimestamp()) { timestampProperty = propertyDescriptor; timestampValue = propertyDescriptor.GetValue(entity); continue; } object val = propertyDescriptor.GetValue(entity); if (entityState != null && !entityState.HasChanged(propertyDescriptor, val)) { continue; } DbExpression valExp = DbExpression.Parameter(val, propertyDescriptor.PropertyType, propertyDescriptor.Column.DbType); updateColumns.Add(propertyDescriptor, valExp); } if (updateColumns.Count == 0) { return(0); } DbTable dbTable = table == null ? typeDescriptor.Table : new DbTable(table, typeDescriptor.Table.Schema); if (timestampValue != null) { keyValueMap[timestampProperty] = timestampValue; } DbExpression conditionExp = PrimaryKeyHelper.MakeCondition(keyValueMap, dbTable); DbUpdateExpression e = new DbUpdateExpression(dbTable, conditionExp); foreach (var item in updateColumns) { e.UpdateColumns.Add(item.Key.Column, item.Value); } int rowsAffected = 0; if (timestampValue == null) { rowsAffected = this.ExecuteNonQuery(e); if (entityState != null) { entityState.Refresh(); } return(rowsAffected); } List <Action <TEntity, IDataReader> > mappers = new List <Action <TEntity, IDataReader> >(); mappers.Add(GetMapper <TEntity>(timestampProperty, e.Returns.Count)); e.Returns.Add(timestampProperty.Column); IDataReader dataReader = this.ExecuteReader(e); using (dataReader) { while (dataReader.Read()) { rowsAffected++; foreach (var mapper in mappers) { mapper(entity, dataReader); } } } if (entityState != null) { entityState.Refresh(); } return(rowsAffected); }
/// <summary> /// 执行通用删除操作 /// </summary> /// <param name="entity">要删除的实体</param> /// <param name="isSave">是否保存</param> /// <returns>返回受影响的行数</returns> public int Delete(TEntity entity, bool isSave = true) { PublicHelper.CheckArgument(entity, "entity"); _efContext.RegisterDelete(entity); return(isSave ? _efContext.Commit() : 0); }
public override object Insert <TEntity>(Expression <Func <TEntity> > content, string table) { PublicHelper.CheckNull(content); TypeDescriptor typeDescriptor = EntityTypeContainer.GetDescriptor(typeof(TEntity)); if (typeDescriptor.PrimaryKeys.Count > 1) { /* 对于多主键的实体,暂时不支持调用这个方法进行插入 */ throw new NotSupportedException(string.Format("Can not call this method because entity '{0}' has multiple keys.", typeDescriptor.Definition.Type.FullName)); } PropertyDescriptor keyPropertyDescriptor = typeDescriptor.PrimaryKeys.FirstOrDefault(); Dictionary <MemberInfo, Expression> insertColumns = InitMemberExtractor.Extract(content); DbTable explicitDbTable = null; if (table != null) { explicitDbTable = new DbTable(table, typeDescriptor.Table.Schema); } DefaultExpressionParser expressionParser = typeDescriptor.GetExpressionParser(explicitDbTable); DbInsertExpression insertExp = new DbInsertExpression(explicitDbTable ?? typeDescriptor.Table); object keyVal = null; foreach (var kv in insertColumns) { MemberInfo key = kv.Key; PropertyDescriptor propertyDescriptor = typeDescriptor.TryGetPropertyDescriptor(key); if (propertyDescriptor == null) { throw new ChloeException(string.Format("The member '{0}' does not map any column.", key.Name)); } if (propertyDescriptor.IsAutoIncrement) { throw new ChloeException(string.Format("Could not insert value into the identity column '{0}'.", propertyDescriptor.Column.Name)); } if (propertyDescriptor.HasSequence()) { throw new ChloeException(string.Format("Can not insert value into the column '{0}', because it's mapping member has define a sequence.", propertyDescriptor.Column.Name)); } if (propertyDescriptor.IsPrimaryKey) { object val = ExpressionEvaluator.Evaluate(kv.Value); if (val == null) { throw new ChloeException(string.Format("The primary key '{0}' could not be null.", propertyDescriptor.Property.Name)); } else { keyVal = val; insertExp.InsertColumns.Add(propertyDescriptor.Column, DbExpression.Parameter(keyVal, propertyDescriptor.PropertyType, propertyDescriptor.Column.DbType)); continue; } } insertExp.InsertColumns.Add(propertyDescriptor.Column, expressionParser.Parse(kv.Value)); } foreach (var item in typeDescriptor.PropertyDescriptors.Where(a => a.HasSequence())) { DbMethodCallExpression getNextValueForSequenceExp = PublicHelper.MakeNextValueForSequenceDbExpression(item); insertExp.InsertColumns.Add(item.Column, getNextValueForSequenceExp); } if (keyPropertyDescriptor != null) { //主键为空并且主键又不是自增列 if (keyVal == null && !keyPropertyDescriptor.IsAutoIncrement && !keyPropertyDescriptor.HasSequence()) { throw new ChloeException(string.Format("The primary key '{0}' could not be null.", keyPropertyDescriptor.Property.Name)); } } if (keyPropertyDescriptor == null) { this.ExecuteNonQuery(insertExp); return(keyVal); /* It will return null if an entity does not define primary key. */ } if (!keyPropertyDescriptor.IsAutoIncrement && !keyPropertyDescriptor.HasSequence()) { this.ExecuteNonQuery(insertExp); return(keyVal); } IDbExpressionTranslator translator = this.DatabaseProvider.CreateDbExpressionTranslator(); List <DbParam> parameters; string sql = translator.Translate(insertExp, out parameters); if (keyPropertyDescriptor.IsAutoIncrement) { /* 自增 id 不能用 output inserted.Id 输出,因为如果表设置了触发器的话会报错 */ sql = string.Concat(sql, ";", this.GetSelectLastInsertIdClause()); } else if (keyPropertyDescriptor.HasSequence()) { insertExp.Returns.Add(keyPropertyDescriptor.Column); } object ret = this.Session.ExecuteScalar(sql, parameters.ToArray()); if (ret == null || ret == DBNull.Value) { throw new ChloeException("Unable to get the identity/sequence value."); } ret = PublicHelper.ConvertObjType(ret, typeDescriptor.AutoIncrement.PropertyType); return(ret); }
/// <summary> /// Set progress. /// </summary> private void SetProgress(ulong total, ulong transfered) { if (InvokeRequired) { object[] args = { total, transfered }; BeginInvoke(new CbGeneric <ulong, ulong>(SetProgress), args); } else { progressBar.Maximum = 1000; progressBar.Value = (int)(transfered * 1000 / total); TimeSpan span = DateTime.Now - mLatestShowTime; if (span.TotalSeconds >= 1) { mLatestShowTime = DateTime.Now; label_Progress.Text = string.Format("{0}/{1}", PublicHelper.GetSizeString(transfered), PublicHelper.GetSizeString(total)); } } }
/// <summary> /// 查找指定主键的实体记录 /// </summary> /// <param name="key">指定主键</param> /// <returns>符合编号的记录,不存在返回null</returns> public TEntity GetByKey(object key) { PublicHelper.CheckArgument(key, "key"); return(_efContext.Set <TEntity>().Find(key)); }
public PostgreSQLContext(IDbConnectionFactory dbConnectionFactory) { PublicHelper.CheckNull(dbConnectionFactory); this._databaseProvider = new DatabaseProvider(dbConnectionFactory, this); }
public override TEntity Insert <TEntity>(TEntity entity, string table) { PublicHelper.CheckNull(entity); TypeDescriptor typeDescriptor = EntityTypeContainer.GetDescriptor(typeof(TEntity)); DbTable dbTable = PublicHelper.CreateDbTable(typeDescriptor, table); Dictionary <PrimitivePropertyDescriptor, object> keyValueMap = PrimaryKeyHelper.CreateKeyValueMap(typeDescriptor); Dictionary <PrimitivePropertyDescriptor, DbExpression> insertColumns = new Dictionary <PrimitivePropertyDescriptor, DbExpression>(); foreach (PrimitivePropertyDescriptor propertyDescriptor in typeDescriptor.PrimitivePropertyDescriptors) { if (propertyDescriptor.IsAutoIncrement) { continue; } if (propertyDescriptor.HasSequence()) { DbMethodCallExpression getNextValueForSequenceExp = PublicHelper.MakeNextValueForSequenceDbExpression(propertyDescriptor, dbTable.Schema); insertColumns.Add(propertyDescriptor, getNextValueForSequenceExp); continue; } object val = propertyDescriptor.GetValue(entity); PublicHelper.NotNullCheck(propertyDescriptor, val); if (propertyDescriptor.IsPrimaryKey) { keyValueMap[propertyDescriptor] = val; } DbParameterExpression valExp = DbExpression.Parameter(val, propertyDescriptor.PropertyType, propertyDescriptor.Column.DbType); insertColumns.Add(propertyDescriptor, valExp); } PrimitivePropertyDescriptor nullValueKey = keyValueMap.Where(a => a.Value == null && !a.Key.IsAutoIncrement).Select(a => a.Key).FirstOrDefault(); if (nullValueKey != null) { /* 主键为空并且主键又不是自增列 */ throw new ChloeException(string.Format("The primary key '{0}' could not be null.", nullValueKey.Property.Name)); } DbInsertExpression insertExp = new DbInsertExpression(dbTable); foreach (var kv in insertColumns) { insertExp.InsertColumns.Add(kv.Key.Column, kv.Value); } List <Action <TEntity, IDataReader> > mappers = new List <Action <TEntity, IDataReader> >(); foreach (var item in typeDescriptor.PrimitivePropertyDescriptors.Where(a => a.IsAutoIncrement || a.HasSequence())) { mappers.Add(GetMapper <TEntity>(item, insertExp.Returns.Count)); insertExp.Returns.Add(item.Column); } if (mappers.Count == 0) { this.ExecuteNonQuery(insertExp); return(entity); } IDbExpressionTranslator translator = this.DatabaseProvider.CreateDbExpressionTranslator(); List <DbParam> parameters; string sql = translator.Translate(insertExp, out parameters); IDataReader dataReader = this.Session.ExecuteReader(sql, parameters.ToArray()); using (dataReader) { dataReader.Read(); foreach (var mapper in mappers) { mapper(entity, dataReader); } } return(entity); }
public MySqlContext(IDbConnectionFactory dbConnectionFactory) { PublicHelper.CheckNull(dbConnectionFactory); this._databaseProvider = new DatabaseProvider(dbConnectionFactory); }
/// <summary> /// 设置UI显示的进度表。 /// </summary> private void SetProgress(ulong total, ulong transmitted) { if (this.InvokeRequired) { object[] args = { total, transmitted }; this.BeginInvoke(new CbGeneric <ulong, ulong>(this.SetProgress), args); } else { this.progressBar1.Maximum = 1000; this.progressBar1.Value = (int)(transmitted * 1000 / total); TimeSpan span = DateTime.Now - this.lastShowTime; if (span.TotalSeconds >= 1) { this.lastShowTime = DateTime.Now; this.label_progress.Text = string.Format("{0}/{1}", PublicHelper.GetSizeString(transmitted), PublicHelper.GetSizeString(total)); } } }
/// <summary> /// 批量插入实体记录集合 /// </summary> /// <param name="entities"> 实体记录集合 </param> /// <param name="isSave"> 是否执行保存 </param> /// <returns> 操作影响的行数 </returns> public virtual int Insert(IEnumerable <TEntity> entities, bool isSave = true) { PublicHelper.CheckArgument(entities, "entities"); EFContext.RegisterNew <TEntity, TKey>(entities); return(isSave ? EFContext.Commit() : 0); }
/// <summary> /// 插入实体记录 /// </summary> /// <param name="entity"> 实体对象 </param> /// <param name="isSave"> 是否执行保存 </param> /// <returns> 操作影响的行数 </returns> public virtual int Insert(TEntity entity, bool isSave = true) { PublicHelper.CheckArgument(entity, "entity"); EFContext.RegisterNew <TEntity, TKey>(entity); return(isSave ? EFContext.Commit() : 0); }
/// <summary> /// 查找指定主键的实体记录 /// </summary> /// <param name="key"> 指定主键 </param> /// <returns> 符合编号的记录,不存在返回null </returns> public virtual TEntity GetByKey(TKey key) { PublicHelper.CheckArgument(key, "key"); return(EFContext.Set <TEntity, TKey>().Find(key)); }
protected void Button1_Click(object sender, EventArgs e) { //生成会员,没有就成no_name会员 //生成主订单 double order_amount = Convert.ToDouble(TextRealMoney.Text); if (order_amount <= 0 || order_amount > all_sales) { JSHelper.WriteScript("alert('实收金额有误');history.back();"); return; } double order_plus = 0; order_plus = all_sales - order_amount; SqlHelper helper = LocalSqlHelper.WH; string order_sql = "select * from dbo.Direct_OrderMain where shopxpacid=@shopxpacid"; helper.Params.Add("@shopxpacid", trace_id); DataTable order_dt = helper.ExecDataTable(order_sql); if (order_dt.Rows.Count == 0) { Response.Write("传递有误"); Response.End(); } string Sql = "select * from Tb_cashier_cart where cashier_id=@cashier_id and is_return=1 and trace_id=@trace_id"; helper.Params.Add("@cashier_id", my_admin_id); helper.Params.Add("@trace_id", trace_id); DataTable dt = helper.ExecDataTable(Sql); DateTime pay_time = DateTime.Now; string dingdan = order_dt.Rows[0]["dingdan"] + "_" + PublicHelper.ConvertDateTimeInt(pay_time) + "_return"; dingdan = "TH_" + PublicHelper.ConvertDateTimeInt(pay_time); //插入订单商品 for (int i = 0; i < dt.Rows.Count; i++) { helper.Params.Clear(); int p_quantity = Convert.ToInt32(dt.Rows[i]["quantity"]); string p_txm = Convert.ToString(dt.Rows[i]["txm"]); helper.Params.Add("supplierid", StorageHelper.getSupplierIdByTxm(p_txm)); helper.Params.Add("dingdan", dingdan); helper.Params.Add("shopxpptid", Convert.ToInt32(dt.Rows[i]["goods_id"])); helper.Params.Add("style_id", Convert.ToInt32(dt.Rows[i]["spec_id"])); helper.Params.Add("shopxpptname", dt.Rows[i]["goods_name"]); helper.Params.Add("p_size", dt.Rows[i]["specification"]); helper.Params.Add("txm", p_txm); helper.Params.Add("productcount", p_quantity); helper.Params.Add("danjia", Convert.ToDouble(dt.Rows[i]["price"])); helper.Params.Add("voucher", Convert.ToDouble(dt.Rows[i]["voucher_price"])); helper.Params.Add("return_detail_id", dt.Rows[i]["order_goods_id"]); helper.Insert("Direct_OrderDetail"); //更新原单中可退数量 helper.Params.Clear(); helper.Execute("update Direct_OrderDetail set productcount_return=productcount_return+" + (0 - p_quantity) + " where id=" + dt.Rows[i]["order_goods_id"]); StorageHelper.changeStock(my_warehouse_id, Convert.ToInt32(dt.Rows[i]["spec_id"]), 0 - p_quantity, dingdan, "店面销售"); } //生成主订单 helper.Params.Clear(); helper.Params.Add("userid", order_dt.Rows[0]["userid"]); helper.Params.Add("user_name", order_dt.Rows[0]["user_name"]); helper.Params.Add("warehouse_id", order_dt.Rows[0]["warehouse_id"]); helper.Params.Add("store_id", order_dt.Rows[0]["store_id"]); //myStorageInfo.warehouse_name helper.Params.Add("seller_name", order_dt.Rows[0]["userid"]); helper.Params.Add("dingdan", dingdan); helper.Params.Add("dingdan_type", 99); helper.Params.Add("user_type", 0); helper.Params.Add("order_amount", order_amount); helper.Params.Add("order_plus", order_plus); helper.Params.Add("payment_name", DDPaymentName.Text); helper.Params.Add("usertel", order_dt.Rows[0]["usertel"]); helper.Params.Add("liuyan", ""); helper.Params.Add("shopxp_shfs", 0); helper.Params.Add("fksj", pay_time); int OrderStatus = 11;//退货新生成 helper.Params.Add("fhsj", pay_time); helper.Params.Add("zhuangtai", OrderStatus); helper.Params.Add("guide_id", order_dt.Rows[0]["guide_id"]); helper.Params.Add("cashier_id", my_admin_id); helper.Params.Add("is_tiaohuan", 1); helper.Params.Add("return_order_id", trace_id); helper.Insert("Direct_OrderMain"); //清除购物车 helper.Params.Clear(); helper.Params.Add("@cashier_id", my_admin_id); helper.Params.Add("@trace_id", trace_id); helper.Execute("delete from Tb_cashier_cart where cashier_id=@cashier_id and is_return=1 and trace_id=@trace_id"); JSHelper.WriteScript("alert('退单成功');location.href='CashierPrint.aspx?dingdan=" + dingdan + "';"); //Response.Write(RoleList.Text); Response.End(); }
/// <summary> /// 修改任务信息 /// </summary> /// <param name="updateInfo">信息</param> /// <returns>业务操作结果</returns> public virtual OperationResult UpdateTask(Task TaskInfo) { PublicHelper.CheckArgument(TaskInfo, "updateInfo"); ReleaseTaskRepository.Update(TaskInfo); return(new OperationResult(OperationResultType.Success, "修改成功。")); }
public virtual OperationResult FindEntity(string key) { PublicHelper.CheckArgument(key, "ecsg"); return(ecsgRepository.GetByKey(key)); }
protected override async Task InsertRange <TEntity>(List <TEntity> entities, string table, bool @async) { /* * 将 entities 分批插入数据库 * 每批生成 insert into TableName(...) select ... union all select ... * 该方法相对循环一条一条插入,速度提升 1/2 这样 */ PublicHelper.CheckNull(entities); if (entities.Count == 0) { return; } int maxParameters = 1000; int batchSize = 30; /* 每批实体大小,此值通过测试得出相对插入速度比较快的一个值 */ TypeDescriptor typeDescriptor = EntityTypeContainer.GetDescriptor(typeof(TEntity)); List <PrimitivePropertyDescriptor> mappingPropertyDescriptors = typeDescriptor.PrimitivePropertyDescriptors.Where(a => a.IsAutoIncrement == false).ToList(); int maxDbParamsCount = maxParameters - mappingPropertyDescriptors.Count; /* 控制一个 sql 的参数个数 */ DbTable dbTable = PublicHelper.CreateDbTable(typeDescriptor, table); string sqlTemplate = AppendInsertRangeSqlTemplate(dbTable, mappingPropertyDescriptors); Func <Task> insertAction = async() => { int batchCount = 0; List <DbParam> dbParams = new List <DbParam>(); StringBuilder sqlBuilder = new StringBuilder(); for (int i = 0; i < entities.Count; i++) { var entity = entities[i]; if (batchCount > 0) { sqlBuilder.Append(" UNION ALL"); } sqlBuilder.Append(" SELECT "); for (int j = 0; j < mappingPropertyDescriptors.Count; j++) { if (j > 0) { sqlBuilder.Append(","); } PrimitivePropertyDescriptor mappingPropertyDescriptor = mappingPropertyDescriptors[j]; object val = mappingPropertyDescriptor.GetValue(entity); PublicHelper.NotNullCheck(mappingPropertyDescriptor, val); if (val == null) { sqlBuilder.Append("NULL"); continue; } Type valType = val.GetType(); if (valType.IsEnum) { val = Convert.ChangeType(val, Enum.GetUnderlyingType(valType)); valType = val.GetType(); } if (Utils.IsToStringableNumericType(valType)) { sqlBuilder.Append(val.ToString()); continue; } if (val is bool) { if ((bool)val == true) { sqlBuilder.AppendFormat("1"); } else { sqlBuilder.AppendFormat("0"); } continue; } string paramName = UtilConstants.ParameterNamePrefix + dbParams.Count.ToString(); DbParam dbParam = new DbParam(paramName, val) { DbType = mappingPropertyDescriptor.Column.DbType }; dbParams.Add(dbParam); sqlBuilder.Append(paramName); } batchCount++; if ((batchCount >= 20 && dbParams.Count >= 200 /*参数个数太多也会影响速度*/) || dbParams.Count >= maxDbParamsCount || batchCount >= batchSize || (i + 1) == entities.Count) { sqlBuilder.Insert(0, sqlTemplate); string sql = sqlBuilder.ToString(); await this.Session.ExecuteNonQuery(sql, dbParams.ToArray(), @async); sqlBuilder.Clear(); dbParams.Clear(); batchCount = 0; } } }; Func <Task> fAction = insertAction; if (this.Session.IsInTransaction) { await fAction(); return; } /* 因为分批插入,所以需要开启事务保证数据一致性 */ using (var tran = this.BeginTransaction()) { await fAction(); tran.Commit(); } }
/// <summary> /// 执行批量删除指定条件表达式的实体 /// </summary> /// <param name="predicate">要删除的指定表达式</param> /// <param name="isSave">是否保存</param> /// <returns>返回受影响的行数</returns> public int Delete(Expression <Func <TEntity, bool> > predicate, bool isSave = true) { PublicHelper.CheckArgument(predicate, "predicate"); _efContext.RegisterDelete(predicate); return(isSave ? _efContext.Commit() : 0); }
public DataReaderDecorator(IDataReader reader) { PublicHelper.CheckNull(reader); this._reader = reader; }
/// <summary> /// 执行通用批量新增实体集合 /// </summary> /// <param name="entities">要插入的新增实体集</param> /// <param name="isSave">是否保存</param> /// <returns>返回受影响的行数</returns> public int Insert(IEnumerable <TEntity> entities, bool isSave = true) { PublicHelper.CheckArgument(entities, "entity"); _efContext.RegisterNew(entities); return(isSave ? _efContext.Commit() : 0); }
private void LoadDirectory(string path, bool tipOnException) { if (this.ownerID == null) { return; } Cursor old = Cursor.Current; Cursor.Current = Cursors.WaitCursor; try { SharedDirectory sharedDirectory = this.fileDirectoryOutter.GetSharedDirectory(this.ownerID, this.netDiskID, path); if (sharedDirectory == null) { MessageBox.Show("网络硬盘未开放!"); } else if (!sharedDirectory.Valid) { MessageBox.Show(sharedDirectory.Exception); } else { if (path == null) { this.ownerSharedAllDisk = sharedDirectory.DirectoryPath == null; } #region Action this.listView_fileDirectory.Items.Clear(); if (sharedDirectory.DirectoryPath == null) { sharedDirectory.DriveList.Sort(); foreach (DiskDrive drive in sharedDirectory.DriveList) { int imageIndex = 2; if (drive.DriveType == DriveType.CDRom) { imageIndex = 3; } if (drive.DriveType == DriveType.Removable) { imageIndex = 4; } ListViewItem item = new ListViewItem(new string[] { drive.Name, "", "" }, imageIndex); item.Tag = new FileOrDirectoryTag(drive.Name, 0, DateTime.Now, false); string name = drive.VolumeLabel; if (name == null || name.Length == 0) { name = drive.Name; } item.ToolTipText = string.Format("{0}\n可用空间:{1}\n总 大 小:{2}", name, PublicHelper.GetSizeString(drive.AvailableFreeSpace), PublicHelper.GetSizeString(drive.TotalSize)); this.listView_fileDirectory.Items.Add(item); } } else { foreach (DirectoryDetail dirDetail in sharedDirectory.SubDirectorys) { ListViewItem item = new ListViewItem(new string[] { dirDetail.Name, dirDetail.CreateTime.ToString(), "" }, 0); //ListViewItem item = this.listView_fileDirectory.Items.Add(dirName, 0); item.Tag = new FileOrDirectoryTag(dirDetail.Name, 0, dirDetail.CreateTime, false); this.listView_fileDirectory.Items.Add(item); } foreach (FileDetail file in sharedDirectory.FileList) { ListViewItem item = new ListViewItem(new string[] { file.Name, file.CreateTime.ToString(), PublicHelper.GetSizeString((uint)file.Size) }, this.GetIconIndex(file.Name)); //ListViewItem item = this.listView_fileDirectory.Items.Add(file.Name, this.GetIconIndex(file.Name)); item.Tag = new FileOrDirectoryTag(file.Name, file.Size, file.CreateTime, true); item.ToolTipText = string.Format("大 小:{0}\n创建日期:{1}", PublicHelper.GetSizeString((uint)file.Size), file.CreateTime); this.listView_fileDirectory.Items.Add(item); } this.columnIndexToSort = 0; this.asendingOrder = true; this.listView_fileDirectory.Sort(); } this.currentDirPath = path; if (this.currentDirPath != null && !this.currentDirPath.EndsWith("\\")) { this.currentDirPath += "\\"; } string displayPath = this.IsNetworkDisk ? "网络硬盘" : "共享磁盘"; if (this.currentDirPath != null && this.currentDirPath != sharedDirectory.DirectoryPath) { displayPath += "\\" + this.currentDirPath; } this.toolStripTextBox1.Text = displayPath; this.listView_fileDirectory.LabelEdit = (sharedDirectory.DirectoryPath != null); #endregion } } catch (Exception ee) { if (tipOnException) { MessageBox.Show(ee.Message); } } finally { Cursor.Current = old; } }
public ChloeMySqlConnection(IDbConnection dbConnection) { PublicHelper.CheckNull(dbConnection); this._dbConnection = dbConnection; }
//上传文件夹 private void toolStripMenuItem4_Click(object sender, EventArgs e) { try { string dirPath = FileHelper.GetFolderToOpen(false); if (dirPath == null) { return; } ulong dirSize = FileHelper.GetDirectorySize(dirPath); if (this.IsNetworkDisk) { NetworkDiskState state = this.fileDirectoryOutter.GetNetworkDiskState(this.netDiskID); ulong available = state.TotalSize - state.SizeUsed; if (available < dirSize) { MessageBox.Show(string.Format("空间不足!网络硬盘剩余空间为{0},所需空间为{1}!", PublicHelper.GetSizeString(available), PublicHelper.GetSizeString(dirSize))); return; } } string containerPath = this.currentDirPath; string[] names = dirPath.Split('\\'); string dirName = names[names.Length - 1]; this.fileDirectoryOutter.Upload(this.ownerID, this.netDiskID, dirPath, containerPath + dirName); } catch (Exception ee) { MessageBox.Show(ee.Message); } }
public override void InsertRange <TEntity>(List <TEntity> entities, string table) { /* * 将 entities 分批插入数据库 * 每批生成 insert into TableName(...) values(...),(...)... * 该方法相对循环一条一条插入,速度提升 2/3 这样 */ PublicHelper.CheckNull(entities); if (entities.Count == 0) { return; } int maxParameters = 2100; int batchSize = 50; /* 每批实体大小,此值通过测试得出相对插入速度比较快的一个值 */ TypeDescriptor typeDescriptor = EntityTypeContainer.GetDescriptor(typeof(TEntity)); List <PropertyDescriptor> mappingPropertyDescriptors = typeDescriptor.PropertyDescriptors.Where(a => a.IsAutoIncrement == false && !a.IsTimestamp()).ToList(); int maxDbParamsCount = maxParameters - mappingPropertyDescriptors.Count; /* 控制一个 sql 的参数个数 */ DbTable dbTable = string.IsNullOrEmpty(table) ? typeDescriptor.Table : new DbTable(table, typeDescriptor.Table.Schema); string sqlTemplate = AppendInsertRangeSqlTemplate(dbTable, mappingPropertyDescriptors); Action insertAction = () => { int batchCount = 0; List <DbParam> dbParams = new List <DbParam>(); StringBuilder sqlBuilder = new StringBuilder(); for (int i = 0; i < entities.Count; i++) { var entity = entities[i]; if (batchCount > 0) { sqlBuilder.Append(","); } sqlBuilder.Append("("); for (int j = 0; j < mappingPropertyDescriptors.Count; j++) { if (j > 0) { sqlBuilder.Append(","); } PropertyDescriptor mappingPropertyDescriptor = mappingPropertyDescriptors[j]; if (mappingPropertyDescriptor.HasSequence()) { sqlBuilder.Append("NEXT VALUE FOR "); sqlBuilder.Append(mappingPropertyDescriptor.Definition.SequenceName); continue; } object val = mappingPropertyDescriptor.GetValue(entity); if (val == null) { sqlBuilder.Append("NULL"); continue; } Type valType = val.GetType(); if (valType.IsEnum) { val = Convert.ChangeType(val, Enum.GetUnderlyingType(valType)); valType = val.GetType(); } if (Utils.IsToStringableNumericType(valType)) { sqlBuilder.Append(val.ToString()); continue; } if (val is bool) { if ((bool)val == true) { sqlBuilder.AppendFormat("1"); } else { sqlBuilder.AppendFormat("0"); } continue; } string paramName = UtilConstants.ParameterNamePrefix + dbParams.Count.ToString(); DbParam dbParam = new DbParam(paramName, val) { DbType = mappingPropertyDescriptor.Column.DbType }; dbParams.Add(dbParam); sqlBuilder.Append(paramName); } sqlBuilder.Append(")"); batchCount++; if ((batchCount >= 20 && dbParams.Count >= 120 /*参数个数太多也会影响速度*/) || dbParams.Count >= maxDbParamsCount || batchCount >= batchSize || (i + 1) == entities.Count) { sqlBuilder.Insert(0, sqlTemplate); string sql = sqlBuilder.ToString(); this.Session.ExecuteNonQuery(sql, dbParams.ToArray()); sqlBuilder.Clear(); dbParams.Clear(); batchCount = 0; } } }; if (this.Session.IsInTransaction) { insertAction(); } else { /* 因为分批插入,所以需要开启事务保证数据一致性 */ this.Session.BeginTransaction(); try { insertAction(); this.Session.CommitTransaction(); } catch { if (this.Session.IsInTransaction) { this.Session.RollbackTransaction(); } throw; } } }
private void 文件ToolStripMenuItem_Click(object sender, EventArgs e) { try { string filePath = FileHelper.GetFileToOpen("请选择要上传的文件"); if (filePath == null) { return; } string fileName = FileHelper.GetFileNameNoPath(filePath); foreach (ListViewItem item in this.listView_fileDirectory.Items) { if (((FileOrDirectoryTag)item.Tag).IsFile && item.Text.ToLower() == fileName.ToLower()) { if (!WindowsHelper.ShowQuery(string.Format("{0}已经存在,确定要覆盖它吗?", fileName))) { return; } } } if (this.IsNetworkDisk) { ulong fileSize = FileHelper.GetFileSize(filePath); NetworkDiskState state = this.fileDirectoryOutter.GetNetworkDiskState(this.netDiskID); ulong available = state.TotalSize - state.SizeUsed; if (available < fileSize) { MessageBox.Show(string.Format("网络硬盘剩余空间为{0},无法上传大小为{1}的文件!", PublicHelper.GetSizeString(available), PublicHelper.GetSizeString(fileSize))); return; } } this.fileDirectoryOutter.Upload(this.ownerID, this.netDiskID, filePath, this.currentDirPath + fileName); } catch (Exception ee) { MessageBox.Show(ee.Message); } }
/// <summary> /// 利用 SqlBulkCopy 批量插入数据。 /// </summary> /// <typeparam name="TEntity"></typeparam> /// <param name="entities"></param> /// <param name="table"></param> /// <param name="batchSize">设置 SqlBulkCopy.BatchSize 的值</param> /// <param name="bulkCopyTimeout">设置 SqlBulkCopy.BulkCopyTimeout 的值</param> /// <param name="keepIdentity">是否保留源自增值。false 由数据库分配自增值</param> public virtual void BulkInsert <TEntity>(List <TEntity> entities, string table = null, int?batchSize = null, int?bulkCopyTimeout = null, bool keepIdentity = false) { PublicHelper.CheckNull(entities); TypeDescriptor typeDescriptor = EntityTypeContainer.GetDescriptor(typeof(TEntity)); DataTable dtToWrite = ConvertToSqlBulkCopyDataTable(entities, typeDescriptor); bool shouldCloseConnection = false; SqlConnection conn = this.Session.CurrentConnection as SqlConnection; try { SqlTransaction externalTransaction = null; if (this.Session.IsInTransaction) { externalTransaction = this.Session.CurrentTransaction as SqlTransaction; } SqlBulkCopyOptions sqlBulkCopyOptions = SqlBulkCopyOptions.CheckConstraints | SqlBulkCopyOptions.KeepNulls | SqlBulkCopyOptions.FireTriggers; if (keepIdentity) { sqlBulkCopyOptions = SqlBulkCopyOptions.KeepIdentity | sqlBulkCopyOptions; } SqlBulkCopy sbc = new SqlBulkCopy(conn, sqlBulkCopyOptions, externalTransaction); using (sbc) { for (int i = 0; i < dtToWrite.Columns.Count; i++) { var column = dtToWrite.Columns[i]; sbc.ColumnMappings.Add(column.ColumnName, column.ColumnName); } if (batchSize != null) { sbc.BatchSize = batchSize.Value; } DbTable dbTable = string.IsNullOrEmpty(table) ? typeDescriptor.Table : new DbTable(table, typeDescriptor.Table.Schema); sbc.DestinationTableName = AppendTableName(dbTable); if (bulkCopyTimeout != null) { sbc.BulkCopyTimeout = bulkCopyTimeout.Value; } if (conn.State != ConnectionState.Open) { conn.Open(); shouldCloseConnection = true; } sbc.WriteToServer(dtToWrite); } } finally { if (conn != null) { if (shouldCloseConnection && conn.State == ConnectionState.Open) { conn.Close(); } } } }
private void listView_fileDirectory_DragDrop(object sender, DragEventArgs e) { if ((this.ownerSharedAllDisk || this.IsNetworkDisk) && this.currentDirPath == null) { return; } try { string containerPath = this.currentDirPath; ListViewHitTestInfo containerInfo = this.listView_fileDirectory.HitTest(this.PointToClient(new Point(e.X, e.Y))); if (containerInfo.Item != null && !((FileOrDirectoryTag)containerInfo.Item.Tag).IsFile) { containerPath += containerInfo.Item.Text + "\\"; } ListViewItem targetItem = (ListViewItem)e.Data.GetData(typeof(ListViewItem)); if (targetItem != null) { #region 内部拖动 if (targetItem == containerInfo.Item) { return; } if (containerPath != this.currentDirPath) { if (this.ExistSameNameItem(containerPath, targetItem.Text)) { MessageBox.Show("目标目录中存在同名文件或文件夹,请更改名称后重试!"); return; } } List <string> fileNames = new List <string>(); List <string> dirNames = new List <string>(); if (((FileOrDirectoryTag)targetItem.Tag).IsFile) { fileNames.Add(targetItem.Text); } else { dirNames.Add(targetItem.Text); } OperationResult result = null; if ((Control.ModifierKeys & Keys.Control) == Keys.Control) { result = this.fileDirectoryOutter.Copy(this.ownerID, this.netDiskID, this.currentDirPath, fileNames, dirNames, containerPath); } else { if (this.currentDirPath != containerPath) { result = this.fileDirectoryOutter.Move(this.ownerID, this.netDiskID, this.currentDirPath, fileNames, dirNames, containerPath); } } if (result != null && !result.Succeed) { MessageBox.Show(result.ErrorMessage); } this.LoadDirectory(this.currentDirPath, true); #endregion return; } if (e.Data.GetDataPresent(DataFormats.FileDrop)) { #region 从外部拖入 string[] fileOrDirs = (string[])e.Data.GetData(DataFormats.FileDrop); if (!this.allowUploadFolder) { foreach (string fileOrDirPath in fileOrDirs) { if (Directory.Exists(fileOrDirPath)) { MessageBox.Show("不能够上传文件夹。"); return; } } } ulong fileSize = 0; foreach (string fileOrDirPath in fileOrDirs) { if (File.Exists(fileOrDirPath)) { fileSize += FileHelper.GetFileSize(fileOrDirPath); } if (Directory.Exists(fileOrDirPath)) { fileSize += FileHelper.GetDirectorySize(fileOrDirPath); } string fileOrDirName = FileHelper.GetFileNameNoPath(fileOrDirPath); if (this.ExistSameNameItem(containerPath, fileOrDirName)) { MessageBox.Show("目标目录中存在同名文件或文件夹,请更改名称后重新上传!"); return; } } if (this.IsNetworkDisk) { NetworkDiskState state = this.fileDirectoryOutter.GetNetworkDiskState(this.netDiskID); ulong available = state.TotalSize - state.SizeUsed; if (available < fileSize) { MessageBox.Show(string.Format("空间不足!网络硬盘剩余空间为{0},所需空间为{1}!", PublicHelper.GetSizeString(available), PublicHelper.GetSizeString(fileSize))); return; } } foreach (string fileOrDirPath in fileOrDirs) { if (File.Exists(fileOrDirPath)) { string fileName = FileHelper.GetFileNameNoPath(fileOrDirPath); this.fileDirectoryOutter.Upload(this.ownerID, this.netDiskID, fileOrDirPath, containerPath + fileName); } if (Directory.Exists(fileOrDirPath)) { string[] names = fileOrDirPath.Split('\\'); string dirName = names[names.Length - 1]; this.fileDirectoryOutter.Upload(this.ownerID, this.netDiskID, fileOrDirPath, containerPath + dirName); //this.UploadDirectory(filePath, containerPath); } } #endregion } } catch (Exception ee) { MessageBox.Show(ee.Message); } }
public IGroupingQuery <T> GroupBy <K>(Expression <Func <T, K> > keySelector) { PublicHelper.CheckNull(keySelector); return(new GroupingQuery <T>(this, keySelector)); }
public object ExecuteScalar(string cmdText, object parameter) { return(this.ExecuteScalar(cmdText, PublicHelper.BuildParams(this._dbContext, parameter))); }