public async Task HandleAsync(UserDisplayNameChangedEvent message) { var accountId = message.AggregateRootKey.ToString(); var updateCriteria = new UpdateCriteria <AccountTableObject> { { x => x.DisplayName, message.DisplayName } }; Expression <Func <AccountTableObject, bool> > updateSpecification = x => x.Id == accountId; await gateway.UpdateAsync <AccountTableObject>(updateCriteria, updateSpecification); }
/// <summary> /// Saves the collection. /// </summary> /// <param name="collection">The collection.</param> /// <param name="criteria">The criteria.</param> /// <param name="affect">The affect.</param> /// <param name="selectBack">The select back.</param> /// <returns></returns> public int SaveCollection(ICollection <T> collection, UpdateCriteria criteria, UpdateAffect affect, SelectBack selectBack) { var result = TrySaveCollection(collection, criteria, affect, selectBack); if ((result.Conflicted.Count > 0) || (result.Failed.Count > 0)) { throw new CollectionSaveException <T>(result); } return(result.Inserted.Count + result.Updated.Count); }
private void okBtn_Click(object sender, EventArgs e) { try { string stationNo = string.Empty; if (GlobalAccess.StationNo == "1202") { stationNo = "1105"; } else if (GlobalAccess.StationNo == "2209") { stationNo = "2104"; } else if (GlobalAccess.StationNo == "2206") { stationNo = "2103"; } else if (GlobalAccess.StationNo == "3202") { stationNo = "3101"; } else if (GlobalAccess.StationNo == "3205") { stationNo = "3102"; } else if (GlobalAccess.StationNo == "1212") { stationNo = "1106"; } else if (GlobalAccess.StationNo == "1215") { stationNo = "1107"; } else if (GlobalAccess.StationNo == "1218") { stationNo = "1108"; } UpdateCriteria uc = new UpdateCriteria(typeof(FNHANSOEntity)); Condition c = uc.GetNewCondition(); c.AddEqualTo(FNHANSOEntity.__MOTOSTNO, stationNo); c.AddEqualTo(FNHANSOEntity.__HJYOTAIFLG, "0"); uc.AddAttributeForUpdate(FNHANSOEntity.__HJYOTAIFLG, "1"); uc.Perform(); DbAccess.callAfterStockin(string.Empty); this.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
/// <summary> /// Tries to update the specified object /// </summary> /// <param name="obj">The object.</param> /// <param name="criteria">The criteria of type <see cref="Zonkey.UpdateCriteria"/>.</param> /// <param name="affect">The <see cref="Zonkey.UpdateAffect"/> value that determines which rows to affect.</param> /// <param name="selectBack">The <see cref="Zonkey.SelectBack"/> value that determines whether to select back the changed rows.</param> /// <returns>A <see cref="Zonkey.SaveResult"/> value based on the outcome of the update operation.</returns> public SaveResult TryUpdate(T obj, UpdateCriteria criteria, UpdateAffect affect, SelectBack selectBack) { try { DbCommand[] commands = CommandBuilder.GetUpdateCommands(obj, criteria, affect, selectBack); return(UpdateInternal(obj, commands, (selectBack != SelectBack.None))); } catch (DataException) { throw; } catch (Exception ex) { throw new DataException(ex.Message, ex); } }
public async Task HandleAsync(InvitationCompletedEvent message) { InvitationEndReason reason = message.Accepted ? InvitationEndReason.Accepted : InvitationEndReason.Rejected; var updateCriteria = new UpdateCriteria <NetworkTableObject> { { x => x.InvitationEndDate, message.Timestamp }, { x => x.InvitationEndReason, reason } }; var originatorId = message.OriginatorId.ToString(); var targetUserId = message.TargetUserId.ToString(); Expression <Func <NetworkTableObject, bool> > specification = x => x.OriginatorId == originatorId && x.TargetId == targetUserId; await this.tableGateway.UpdateAsync <NetworkTableObject>(updateCriteria, specification); }
public static void UpdateFngset(string scheduleNo) { IDataParameter[] paras = new IDataParameter[3]; OleDbParameter para = (OleDbParameter)Query.GetParameter("ykk"); para.OleDbType = OleDbType.VarChar; para.ParameterName = "@io_datetime"; para.Value = 0; para.Size = 14; para.Direction = ParameterDirection.InputOutput; paras[0] = para; para = (OleDbParameter)Query.GetParameter("ykk"); para.OleDbType = OleDbType.Integer; para.ParameterName = "@io_return_code"; para.Value = 0; para.Size = 9; para.Direction = ParameterDirection.InputOutput; paras[1] = para; para = (OleDbParameter)Query.GetParameter("ykk"); para.OleDbType = OleDbType.VarChar; para.ParameterName = "@io_return_message"; para.Value = string.Empty; para.Size = 255; para.Direction = ParameterDirection.InputOutput; paras[2] = para; Query.RunProcedure("get_system_datetime", paras, "ykk"); if (Int32.Parse(paras[1].Value.ToString()) != 0) { throw new Exception(paras[2].Value.ToString()); } string datetime = paras[0].Value.ToString(); if (String.IsNullOrEmpty(scheduleNo)) { return; } UpdateCriteria uc = new UpdateCriteria(typeof(FNGSETEntity)); Condition c = uc.GetNewCondition(); c.AddEqualTo(FNGSETEntity.__SCHNO, scheduleNo); uc.AddAttributeForUpdate(FNGSETEntity.__SYORIFLG, "1"); uc.AddAttributeForUpdate(FNGSETEntity.__SAKUSEIHIJI, datetime); uc.Perform(); }
public void EndRelist(tb_MessageQueueEntity mqe,tb_RelistReslutEntity rre) { Transaction t = new Transaction(); UpdateCriteria uc = new UpdateCriteria(typeof(tb_MessageQueueEntity)); Condition c = uc.GetNewCondition(); c.AddEqualTo(tb_MessageQueueEntity.__ID,mqe.id); uc.AddAttributeForUpdate(tb_MessageQueueEntity.__STATE,true); t.AddUpdateCriteria(uc); t.AddSaveObject(rre); try { t.Process(); } catch (PlException plex) { } }
/// <summary> /// Updates the specified object. /// </summary> /// <param name="obj">The object.</param> /// <param name="criteria">The criteria of type <see cref="Zonkey.UpdateCriteria"/>.</param> /// <param name="doSelectBack">if set to <c>true</c> [do select back].</param> /// <returns>A <see cref="Zonkey.SaveResult"/> value based on the outcome of the update operation.</returns> public SaveResult TryUpdate2(T obj, UpdateCriteria criteria, bool doSelectBack) { if (!(obj is ISavable)) { throw new ArgumentException("Update2() is only supported on classes that implement Zonkey.ObjectModel.ISavable", "obj"); } try { DbCommand[] commands = CommandBuilder.GetUpdate2Commands((ISavable)obj, criteria, doSelectBack); return(UpdateInternal(obj, commands, doSelectBack)); } catch (DataException) { throw; } catch (Exception ex) { throw new DataException(ex.Message, ex); } }
public async Task HandleAsync(TextChangedEvent message) { var id = message.AggregateRootKey.ToString(); var updateCriteria = new UpdateCriteria <TextTableObject>(); if (!string.IsNullOrEmpty(message.Title)) { updateCriteria.Add(x => x.Title, message.Title); } if (!string.IsNullOrEmpty(message.Content)) { updateCriteria.Add(x => x.Content, message.Content); } if (updateCriteria.Count == 0) { return; } Expression <Func <TextTableObject, bool> > updateSpecification = x => x.Id == id; await gateway.UpdateAsync <TextTableObject>(updateCriteria, updateSpecification); }
public async Task HandleAsync(UserDisplayNameChangedEvent message) { var userId = message.AggregateRootKey.ToString(); var networkTableUpdateBatch = new List <Tuple <UpdateCriteria <NetworkTableObject>, Specification <NetworkTableObject> > >(); Expression <Func <NetworkTableObject, bool> > originatorEqualsSpecification = x => x.OriginatorId == userId; Expression <Func <NetworkTableObject, bool> > targetUserEqualsSpecification = x => x.TargetId == userId; networkTableUpdateBatch.Add(new Tuple <UpdateCriteria <NetworkTableObject>, Specification <NetworkTableObject> >( new UpdateCriteria <NetworkTableObject> { { x => x.OriginatorName, message.DisplayName } }, originatorEqualsSpecification)); networkTableUpdateBatch.Add(new Tuple <UpdateCriteria <NetworkTableObject>, Specification <NetworkTableObject> >( new UpdateCriteria <NetworkTableObject> { { x => x.TargetUserName, message.DisplayName } }, targetUserEqualsSpecification)); await this.tableGateway.UpdateAsync <NetworkTableObject>(networkTableUpdateBatch); var userNamesTableUpdateCriteria = new UpdateCriteria <UserNameTableObject> { { x => x.DisplayName, message.DisplayName } }; Expression <Func <UserNameTableObject, bool> > userIdSpecification = x => x.UserId == userId; await this.tableGateway.UpdateAsync <UserNameTableObject>(userNamesTableUpdateCriteria, userIdSpecification); }
/// <summary> /// Saves the specified object /// </summary> /// <param name="obj">The object to save</param> /// <param name="criteria">The criteria of type <see cref="Zonkey.UpdateCriteria"/>.</param> /// <param name="affect">The <see cref="Zonkey.UpdateAffect"/> value that determines which rows to affect.</param> /// <param name="selectBack">The <see cref="Zonkey.SelectBack"/> value that determines whether to select back the changed rows.</param> /// <returns>true/false</returns> public bool Save(T obj, UpdateCriteria criteria, UpdateAffect affect, SelectBack selectBack) { return(HandleSaveResult(TrySave(obj, criteria, affect, selectBack))); }
/// <summary> /// Updates the specified object. /// </summary> /// <param name="obj">The object.</param> /// <param name="criteria">The criteria of type <see cref="Zonkey.UpdateCriteria"/>.</param> /// <param name="doSelectBack">if set to <c>true</c> [do select back].</param> /// <returns></returns> public bool Update2(T obj, UpdateCriteria criteria, bool doSelectBack) { return(HandleSaveResult(TryUpdate2(obj, criteria, doSelectBack))); }
/// <summary> /// Saves the collection. /// </summary> /// <param name="collection">The collection.</param> /// <param name="criteria">The criteria of type <see cref="Zonkey.UpdateCriteria"/>.</param> /// <param name="affect">The <see cref="Zonkey.UpdateAffect"/> value that determines which rows to affect.</param> /// <param name="selectBack">The <see cref="Zonkey.SelectBack"/> value that determines whether to select back the changed rows.</param> /// <returns>A value of type <see cref="T:Zonkey.CollectionSaveResult"/></returns> public CollectionSaveResult <T> TrySaveCollection(ICollection <T> collection, UpdateCriteria criteria, UpdateAffect affect, SelectBack selectBack) { var colResult = new CollectionSaveResult <T>(); var bindCol = collection as ITrackDeletedItems <T>; if (bindCol != null) { foreach (T obj in bindCol.DeletedItems) { var objSV = obj as ISavable; if (objSV != null) { if (objSV.DataRowState == DataRowState.Deleted) { DeleteItem(obj); colResult.Deleted.Add(obj); } else { colResult.Skipped.Add(obj); } } else { colResult.Failed.Add(obj); } } } foreach (T obj in collection) { var objSV = obj as ISavable; if (objSV != null) { if (objSV.DataRowState != DataRowState.Unchanged) { switch (TrySave(obj, criteria, affect, selectBack)) { case SaveResult.Skipped: colResult.Skipped.Add(obj); break; case SaveResult.Conflict: colResult.Conflicted.Add(obj); break; case SaveResult.Fail: colResult.Failed.Add(obj); break; case SaveResult.Success: if (_lastSaveSuccessType == 1) { colResult.Inserted.Add(obj); } else { colResult.Updated.Add(obj); } break; } } else { colResult.Skipped.Add(obj); } } else { colResult.Failed.Add(obj); } } return(colResult); }
private void Do() { Query q1 = new Query(typeof(FNCART_CTLEntity)); q1.AddAttribute(FNCART_CTLEntity.__STNO); q1.AddAttribute(FNCART_CTLEntity.__SECTION); q1.AddAttribute(FNCART_CTLEntity.__GROUPNO); Condition c1 = q1.GetQueryCondition(); c1.AddEqualTo(FNCART_CTLEntity.__REGISTER_FLG, "1"); q1.GroupBy(FNCART_CTLEntity.__STNO); q1.GroupBy(FNCART_CTLEntity.__GROUPNO); q1.GroupBy(FNCART_CTLEntity.__SECTION); Query q2 = new Query(typeof(FNRETRIEVAL_STEntity)); q2.AddAttribute(FNRETRIEVAL_STEntity.__RETRIEVAL_STATION); q2.AddAttribute(FNRETRIEVAL_STEntity.__CART_TICKET_PRINTFLG); q2.AddAttribute(FNRETRIEVAL_STEntity.__PRINTER_NO_CART); q2.GroupBy(FNRETRIEVAL_STEntity.__RETRIEVAL_STATION); q2.GroupBy(FNRETRIEVAL_STEntity.__PRINTER_NO_CART); q2.GroupBy(FNRETRIEVAL_STEntity.__CART_TICKET_PRINTFLG); q1.AddJoinQuery(FNCART_CTLEntity.__STNO, q2, FNRETRIEVAL_STEntity.__UNIT_STNO); q1.OrderBy(FNCART_CTLEntity.__STNO); q1.OrderBy(FNCART_CTLEntity.__GROUPNO); DataTable dt = q1.Execute(); //sql1 if (dt != null && dt.Rows.Count > 0) { for (int i = 0; i < dt.Rows.Count; i++) { DataRow dr = dt.Rows[i]; string printflag = dr[FNRETRIEVAL_STEntity.__CART_TICKET_PRINTFLG].ToString(); decimal printNo = Convert.ToDecimal(dr[FNRETRIEVAL_STEntity.__PRINTER_NO_CART]); string printName = GetPrintName(printNo); string retrievalStation = dr[FNRETRIEVAL_STEntity.__RETRIEVAL_STATION].ToString(); string groupNo = dr[FNCART_CTLEntity.__GROUPNO].ToString(); string section = dr[FNCART_CTLEntity.__SECTION].ToString(); try { if (printflag == "1") //要打印 { DataTable dt1 = GetData(section, groupNo); if (dt1 != null && dt1.Rows.Count > 0) { if (retrievalStation == "24") //组立 { AssemblyHead head = new AssemblyHead(); head.Section = section; List <AssemblyDetail> details = new List <AssemblyDetail>(); for (int j = 0; j < dt1.Rows.Count; j++) { DataRow dr1 = dt1.Rows[j]; AssemblyDetail detail = new AssemblyDetail(); detail.BucketNo = dr1[FNCART_CTLEntity.__BUCKET_NO].ToString(); detail.ColorCode = dr1[FNCART_CTLEntity.__COLOR_CODE].ToString(); detail.ItemCode = dr1[FNCART_CTLEntity.__ITEM_CODE].ToString(); detail.ItemName = dr1[FMZKEYEntity.__ZKNAME1].ToString(); detail.Qty = dr1[FNCART_CTLEntity.__QTY].ToString(); detail.Weight = dr1[FNCART_CTLEntity.__WEIGHT].ToString(); details.Add(detail); } pc.DoPrint(printName, head, details); } else if (retrievalStation == "11" || retrievalStation == "21") //SI { SIHead head = new SIHead(); head.Section = section; List <SIDetail> details = new List <SIDetail>(); for (int j = 0; j < dt1.Rows.Count; j++) { DataRow dr1 = dt1.Rows[j]; SIDetail detail = new SIDetail(); detail.BucketNo = dr1[FNCART_CTLEntity.__BUCKET_NO].ToString(); detail.Line = dr1[FNCART_CTLEntity.__LINE].ToString(); detail.ItemCode = dr1[FNCART_CTLEntity.__ITEM_CODE].ToString(); detail.ItemName = dr1[FMZKEYEntity.__ZKNAME1].ToString(); detail.Qty = dr1[FNCART_CTLEntity.__QTY].ToString(); detail.Weight = dr1[FNCART_CTLEntity.__WEIGHT].ToString(); details.Add(detail); } pc.DoPrint(printName, head, details); } } } } catch (Exception ex) { WriteLog(ex.Message); } //update UpdateCriteria uc = new UpdateCriteria(typeof(FNCART_CTLEntity)); Condition c = uc.GetNewCondition(); c.AddEqualTo(FNCART_CTLEntity.__SECTION, section); c.AddEqualTo(FNCART_CTLEntity.__GROUPNO, groupNo); c.AddEqualTo(FNCART_CTLEntity.__REGISTER_FLG, "1"); uc.AddAttributeForUpdate(FNCART_CTLEntity.__REGISTER_FLG, "3"); uc.Perform(); } } }
/// <summary> /// Saves the collection. /// </summary> /// <param name="collection">The collection.</param> /// <param name="criteria">The criteria.</param> /// <param name="continueOnError">if set to <c>true</c> continues past errors.</param> /// <returns>A value of type <see cref="Zonkey.CollectionSaveResult{T}"/></returns> public CollectionSaveResult <T> TrySaveCollection(ICollection <T> collection, UpdateCriteria criteria, bool continueOnError) { return(TrySaveCollection(collection, criteria, UpdateAffect.ChangedFields, SelectBack.Default, false)); }
public DbCommand[] GetUpdateCommands(object obj, UpdateCriteria criteria, UpdateAffect affect, SelectBack selectBack) { if (obj == null) { throw new ArgumentNullException("obj"); } if (obj.GetType() != _dataObjectType) { throw new ArgumentException("Type of 'obj' does not match type from constructor."); } // set update criteria - default is changed fields if (criteria == UpdateCriteria.Default) { criteria = (_dataMap.DataItem.UpdateCriteria == UpdateCriteria.Default) ? UpdateCriteria.ChangedFields : _dataMap.DataItem.UpdateCriteria; } if ((criteria == UpdateCriteria.KeyAndVersion) && (!_dialect.SupportsRowVersion)) { criteria = UpdateCriteria.ChangedFields; } // set select back default if (selectBack == SelectBack.Default) { selectBack = (_dataMap.DataItem.SelectBack == SelectBack.Default) ? SelectBack.UnchangedFields : _dataMap.DataItem.SelectBack; } // get savable obj var objSV = obj as ISavable; if (objSV == null) { affect = UpdateAffect.AllFields; if (selectBack == SelectBack.UnchangedFields) { selectBack = SelectBack.AllFields; } if (criteria == UpdateCriteria.ChangedFields) { criteria = UpdateCriteria.KeyOnly; } } // init command array DbCommand updateCommand = GetTextCommand(""); // create string builders and param lists var setString = new StringBuilder(); var setParmList = new List <DbParameter>(); var whereString = new StringBuilder(); var whereParmList = new List <DbParameter>(); var selectString = new StringBuilder(); var keyString = new StringBuilder(); var keyParmList = new List <DbParameter>(); foreach (IDataMapField field in _dataMap.DataFields) { PropertyInfo pi = field.Property; if (pi == null) { continue; } bool hasChanged = (objSV != null) ? HasFieldChanged(pi, objSV) : true; string sFieldDescr = _dialect.FormatFieldName(field.FieldName, (field.UseQuotedIdentifier ?? UseQuotedIdentifier)); if (selectBack > SelectBack.None) { if (field.IsKeyField) { DbParameter keyParam = CreateWhereParam(updateCommand, field); if (keyString.Length > 0) { keyString.Append(" AND "); } keyString.Append(sFieldDescr); keyString.Append(" = "); keyString.Append(keyParam.ParameterName); keyParam.Value = pi.GetValue(obj, null); keyParmList.Add(keyParam); } else if ((selectBack == SelectBack.AllFields) || ((selectBack == SelectBack.UnchangedFields) && (!hasChanged)) || ((selectBack >= SelectBack.IdentityOrVersion) && (field.IsRowVersion))) { if (selectString.Length > 0) { selectString.Append(", "); } selectString.Append(sFieldDescr); } } if (field.IsKeyField || (hasChanged && (criteria >= UpdateCriteria.ChangedFields)) || (field.IsRowVersion && (criteria == UpdateCriteria.KeyAndVersion)) ) { // A primary key or row version if (whereString.Length > 0) { whereString.Append(" AND "); } // get value for parameter object oParmValue; if ((objSV != null) && (objSV.OriginalValues.ContainsKey(pi.Name))) { oParmValue = (objSV.OriginalValues[pi.Name] ?? DBNull.Value); } else { oParmValue = (pi.GetValue(obj, null) ?? DBNull.Value); } // add to command if (Convert.IsDBNull(oParmValue)) { whereString.AppendFormat("{0} IS NULL", sFieldDescr); } else if (!field.IsComparable) { whereString.AppendFormat("{0} IS NOT NULL", sFieldDescr); } else { DbParameter whereParam = CreateWhereParam(updateCommand, field); whereString.Append(sFieldDescr); whereString.Append(" = "); whereString.Append(whereParam.ParameterName); whereParam.Value = oParmValue; whereParmList.Add(whereParam); } } if ((field.IsAutoIncrement) || (field.IsRowVersion) || (field.AccessType == AccessType.ReadOnly)) { continue; } if ((affect == UpdateAffect.ChangedFields) && (!hasChanged)) { continue; } if (setString.Length > 0) { setString.Append(", "); } DbParameter setParm = CreateSetParam(updateCommand, field); setString.Append(sFieldDescr); setString.Append(" = "); setString.Append(setParm.ParameterName); setParm.Value = (pi.GetValue(obj, null) ?? DBNull.Value); setParmList.Add(setParm); } if (setParmList.Count == 0) { return(null); } if (whereString.Length == 0) { throw new InvalidOperationException(String.Format("Class '{0}' does not contain any properties with DataFieldAttributes or none are marked with IsKeyField.", _dataObjectType.FullName)); } updateCommand.CommandText = String.Format("UPDATE {0} SET {1} WHERE {2};", SaveToTable, setString, whereString); updateCommand.Parameters.AddRange(setParmList.ToArray()); updateCommand.Parameters.AddRange(whereParmList.ToArray()); if ((selectBack > SelectBack.None) && (selectString.Length > 0)) { if (keyString.Length == 0) { throw new InvalidOperationException(String.Format("Class '{0}' does not contain any properties with DataFieldAttributes or none are marked with IsKeyField.", _dataObjectType.FullName)); } DbCommand selectCommand = GetTextCommand(""); selectCommand.CommandText = String.Format("SELECT {0} FROM {1} WHERE {2};", selectString, TableName, keyString); selectCommand.Parameters.AddRange(keyParmList.ToArray()); return(new[] { updateCommand, selectCommand }); } // return null index 1 to indicate no select-back return(new[] { updateCommand, null }); }
/// <summary> /// Equivalent to calling DataClassAdapter.Save /// </summary> /// <typeparam name="Tdc">The type of the dc.</typeparam> /// <param name="obj">The obj.</param> /// <param name="updateCriteria">The update criteria</param> /// <param name="updateAffect">Affect which fields</param> /// <param name="selectBack">Select what back</param> /// <returns></returns> public virtual bool Save <Tdc>(Tdc obj, UpdateCriteria updateCriteria, UpdateAffect updateAffect, SelectBack selectBack) where Tdc : class, ISavable, new() { return(Adapter <Tdc>().Save(obj, updateCriteria, updateAffect, selectBack)); }
/// <summary> /// Equivalent to calling DataClassAdapter.Save /// </summary> /// <typeparam name="Tdc">The type of the dc.</typeparam> /// <param name="obj">The obj.</param> /// <param name="updateCriteria">The update criteria</param> /// <returns></returns> public virtual bool Save <Tdc>(Tdc obj, UpdateCriteria updateCriteria) where Tdc : class, ISavable, new() { return(Adapter <Tdc>().Save(obj, updateCriteria)); }
/// <summary> /// Tries to save the object /// </summary> /// <param name="obj">The object to save</param> /// <param name="criteria">The criteria of type <see cref="Zonkey.UpdateCriteria"/>.</param> /// <returns>A value of type <see cref="Zonkey.SaveResult"/></returns> public SaveResult TrySave(T obj, UpdateCriteria criteria) { return(TrySave(obj, criteria, UpdateAffect.ChangedFields, SelectBack.Default)); }
public DbCommand[] GetUpdate2Commands(ISavable obj, UpdateCriteria criteria, bool doSelectBack) { if (obj == null) { throw new ArgumentNullException("obj"); } if (obj.GetType() != _dataObjectType) { throw new ArgumentException("Type of 'obj' does not match type from constructor."); } if (criteria == UpdateCriteria.AllFields) { throw new ArgumentException("UpdateCriteria.AllFields is not supported by Update2 methods."); } // set update criteria - default is changed fields if (criteria == UpdateCriteria.Default) { criteria = (_dataMap.DataItem.UpdateCriteria == UpdateCriteria.Default) ? UpdateCriteria.ChangedFields : _dataMap.DataItem.UpdateCriteria; } if (criteria == UpdateCriteria.KeyAndVersion) { criteria = UpdateCriteria.ChangedFields; } // check for keys if (_dataMap.KeyFields.Count == 0) { throw new InvalidOperationException(String.Format("Class '{0}' does not contain any properties with DataFieldAttributes or none are marked with IsKeyField.", _dataObjectType.FullName)); } // init commands DbCommand updateCommand = GetTextCommand(""); DbCommand selectCommand = (doSelectBack) ? GetTextCommand("") : null; // create string builders and param lists var setString = new StringBuilder(); var setParmList = new List <DbParameter>(); var whereString = new StringBuilder(); var whereParmList = new List <DbParameter>(); foreach (KeyValuePair <string, object> changedField in obj.OriginalValues) { PropertyInfo pi = _dataObjectType.GetProperty(changedField.Key); if (pi == null) { continue; } IDataMapField field = _dataMap.GetFieldForProperty(pi); if ((field == null) || (field.AccessType == AccessType.ReadOnly)) { continue; } if ((field.IsAutoIncrement) || (field.IsRowVersion)) { continue; } string sFieldDescr = _dialect.FormatFieldName(field.FieldName, (field.UseQuotedIdentifier ?? UseQuotedIdentifier)); if (field.IsKeyField || (criteria >= UpdateCriteria.ChangedFields) || (field.IsRowVersion && (criteria == UpdateCriteria.KeyAndVersion)) ) { // A primary key or row version if (whereString.Length > 0) { whereString.Append(" AND "); } object oParmValue = (changedField.Value ?? DBNull.Value); // add to command if (Convert.IsDBNull(oParmValue)) { whereString.AppendFormat("{0} IS NULL", sFieldDescr); } else if (!field.IsComparable) { whereString.AppendFormat("{0} IS NOT NULL", sFieldDescr); } else { DbParameter whereParam = CreateWhereParam(updateCommand, field); whereString.Append(sFieldDescr); whereString.Append(" = "); whereString.Append(whereParam.ParameterName); whereParam.Value = oParmValue; whereParmList.Add(whereParam); } } if (setString.Length > 0) { setString.Append(", "); } DbParameter setParm = CreateSetParam(updateCommand, field); setString.Append(sFieldDescr); setString.Append(" = "); setString.Append(setParm.ParameterName); if (pi.PropertyType == typeof(string)) { SetStringParamValue(field, setParm, pi.GetValue(obj, null), false); } else { setParm.Value = (pi.GetValue(obj, null) ?? DBNull.Value); } setParmList.Add(setParm); } if (setParmList.Count == 0) { return(null); } var keyString = new StringBuilder(); var keyParmList = new List <DbParameter>(); foreach (IDataMapField field in _dataMap.KeyFields) { PropertyInfo pi = field.Property; if (pi == null) { continue; } string sFieldDescr = _dialect.FormatFieldName(field.FieldName, (field.UseQuotedIdentifier ?? UseQuotedIdentifier)); if (doSelectBack) { DbParameter keyParam = CreateWhereParam(selectCommand, field); if (keyString.Length > 0) { keyString.Append(" AND "); } keyString.Append(sFieldDescr); keyString.Append(" = "); keyString.Append(keyParam.ParameterName); keyParam.Value = pi.GetValue(obj, null); keyParmList.Add(keyParam); } // A primary key or row version if (whereString.Length > 0) { whereString.Append(" AND "); } // get value for parameter object oParmValue; if (obj.OriginalValues.ContainsKey(pi.Name)) { oParmValue = (obj.OriginalValues[pi.Name] ?? DBNull.Value); } else { oParmValue = (pi.GetValue(obj, null) ?? DBNull.Value); } // add to command if (Convert.IsDBNull(oParmValue)) { whereString.AppendFormat("{0} IS NULL", sFieldDescr); } else { DbParameter whereParam = CreateWhereParam(updateCommand, field); whereString.Append(sFieldDescr); whereString.Append(" = "); whereString.Append(whereParam.ParameterName); whereParam.Value = oParmValue; whereParmList.Add(whereParam); } } // setup update command updateCommand.CommandText = String.Format("UPDATE {0} SET {1} WHERE {2};", SaveToTable, setString, whereString); updateCommand.Parameters.AddRange(setParmList.ToArray()); updateCommand.Parameters.AddRange(whereParmList.ToArray()); if (_dialect.SupportsChangeContext && ChangeTrackingContext != null) { _dialect.ApplyChangeTrackingContext(updateCommand, ChangeTrackingContext); } if (!doSelectBack) // if no select-back return now { return new[] { updateCommand, null } } ; // setup select command and return both selectCommand.CommandText = String.Format("SELECT {0} FROM {1} WHERE {2};", ColumnsString, TableName, keyString); selectCommand.Parameters.AddRange(keyParmList.ToArray()); return(new[] { updateCommand, selectCommand }); } }
/// <summary> /// Saves the collection. /// </summary> /// <param name="collection">The collection.</param> /// <param name="criteria">The criteria of type <see cref="Zonkey.UpdateCriteria"/>.</param> /// <param name="affect">The <see cref="Zonkey.UpdateAffect"/> value that determines which rows to affect.</param> /// <param name="selectBack">The <see cref="Zonkey.SelectBack"/> value that determines whether to select back the changed rows.</param> /// <param name="continueOnError">if set to <c>true</c> continues past errors.</param> /// <returns> /// A value of type <see cref="Zonkey.CollectionSaveResult{T}"/> /// </returns> public CollectionSaveResult <T> TrySaveCollection(ICollection <T> collection, UpdateCriteria criteria, UpdateAffect affect, SelectBack selectBack, bool continueOnError) { var colResult = new CollectionSaveResult <T>(); var bindCol = collection as ITrackDeletedItems <T>; if (bindCol != null) { foreach (T obj in bindCol.DeletedItems) { var objSV = obj as ISavable; if (objSV != null) { if (objSV.DataRowState == DataRowState.Deleted) { try { DeleteItem(obj); } catch (Exception ex) { colResult.Exceptions.Add(new CollectionSaveExceptionItem <T>(obj, ex)); if (!continueOnError) { throw; } } colResult.Deleted.Add(obj); } else { colResult.Skipped.Add(obj); } } else { colResult.Failed.Add(obj); } } } foreach (T obj in collection) { var objSV = obj as ISavable; if (objSV != null) { if (objSV.DataRowState != DataRowState.Unchanged) { try { SaveResult saveResult = TrySave(obj, criteria, affect, selectBack); switch (saveResult.Status) { case SaveResultStatus.Skipped: colResult.Skipped.Add(obj); break; case SaveResultStatus.Conflict: colResult.Conflicted.Add(obj); break; case SaveResultStatus.Fail: colResult.Failed.Add(obj); break; case SaveResultStatus.Success: if (saveResult.SaveType == SaveType.Insert) { colResult.Inserted.Add(obj); } else { colResult.Updated.Add(obj); } break; } } catch (Exception ex) { colResult.Exceptions.Add(new CollectionSaveExceptionItem <T>(obj, ex)); if (!continueOnError) { throw; } } } else { colResult.Skipped.Add(obj); } } else { colResult.Failed.Add(obj); } } return(colResult); }
/// <summary> /// Saves the collection. /// </summary> /// <param name="collection">The collection.</param> /// <param name="criteria">The criteria.</param> /// <returns></returns> public int SaveCollection(ICollection <T> collection, UpdateCriteria criteria) { return(SaveCollection(collection, criteria, UpdateAffect.ChangedFields, SelectBack.Default)); }
/// <summary> /// Saves the collection. /// </summary> /// <param name="collection">The collection.</param> /// <param name="criteria">The criteria.</param> /// <returns>A value of type <see cref="T:Zonkey.CollectionSaveResult"/></returns> public CollectionSaveResult <T> TrySaveCollection(ICollection <T> collection, UpdateCriteria criteria) { return(TrySaveCollection(collection, criteria, UpdateAffect.ChangedFields, SelectBack.Default)); }