Exemple #1
0
 internal ExecuteSqlCompleteEventArgs(DbAccess dataAccess, SqlQuery query, DateTime executionStart, DateTime executionFinish, Exception executionException)
     : base(dataAccess, query)
 {
     this.executionStart = executionStart;
     this.executionFinish = executionFinish;
     this.executionException = executionException;
 }
Exemple #2
0
        protected virtual IDataReader CreateDataReader()
        {
            SqlQuery query = new SqlQuery();
            StringBuilder text = query.Text;

            text.Append("SELECT ");
            text.Append(this.DataValueField);
            text.Append(',');
            text.Append(this.DataTextField);
            text.Append(" FROM ");
            text.Append(this.DataTableField);

            if (!String.IsNullOrEmpty(this.FilterExpression))
            {
                text.AppendLine();
                text.Append("WHERE ");
                text.Append(this.FilterExpression);
            }
            if (!String.IsNullOrEmpty(this.SortExpression))
            {
                text.AppendLine();
                text.Append("ORDER BY ");
                text.Append(this.SortExpression);
            }

            return this.Factory.DataAccess.CreateDataReader(query, CommandBehavior.Default);
        }
        private static RecordTable CreateDataSource(GridColumnInfo info, IDbAccess dataAccess)
        {
            SqlQuery query = new SqlQuery();
            StringBuilder text = query.Text;
            text.Append("SELECT ");
            text.Append(info.ParentValueField);
            text.Append(',');
            text.Append(info.ParentTextField);
            text.Append(" FROM ");
            text.Append(info.ParentTable);

            if (!String.IsNullOrEmpty(info.FilterExpression))
            {
                text.Append(" WHERE ");
                text.Append(info.FilterExpression);
            }
            if (!String.IsNullOrEmpty(info.SortExpression))
            {
                text.Append(" ORDER BY ");
                text.Append(info.SortExpression);
            }

            RecordTable table = new RecordTable(info.ParentTable);
            using(IDataReader dr = dataAccess.CreateDataReader(query, CommandBehavior.Default))
            {
                table.Load(dr, false, new UISchemaTableReader(info.ParentValueField));
            }
            return table;
        }
 public static IEnumerable Select(this ICommandAdapter adapter, Type entityType, SqlQuery extendedQuery)
 {
     if (null != adapter && null != entityType)//extendedQuery null olabilir.
     {
         return SelectMethod(entityType).Invoke(adapter, new object[] { extendedQuery }) as IEnumerable;
     }
     return null;
 }
 public static object SelectSingle(this ICommandAdapter adapter, Type entityType, SqlQuery extendedQuery)//extendedQuery null olabilir
 {
     if (null != adapter && null != entityType)
     {
         return SelectSingleMethod(entityType).Invoke(adapter, new object[] { extendedQuery });
     }
     return null;
 }
Exemple #6
0
 //Builder
 public SqlQuery Combine(SqlQuery queryInfo)
 {
     if (null != queryInfo)
     {
         this.text.Append(queryInfo.text);
         this.parameters.AddRange(queryInfo.parameters);
     }
     return this;
 }
Exemple #7
0
        protected virtual void LoadItemsInternal()
        {
            SqlQuery query = new SqlQuery();
            StringBuilder text = query.Text;

            text.Append("SELECT ");
            text.Append(this.ParentValueField);
            text.Append(',');

            string[] arr = this.ParentTextField.Split(',');
            foreach(string s in arr)
            {
                text.Append(s);
                text.Append(',');
            }
            text.Remove(text.Length - 1, 1);

            text.Append(" FROM ");
            text.Append(this.ParentTable);

            if (!String.IsNullOrEmpty(this.FilterExpression))
            {
                text.AppendLine();
                text.Append("WHERE ");
                text.Append(this.FilterExpression);
            }
            if (!String.IsNullOrEmpty(this.SortExpression))
            {
                text.AppendLine();
                text.Append("ORDER BY ");
                text.Append(this.SortExpression);
            }

            base.Items.Clear();
            using (IDataReader dr = this.Factory.DataAccess.CreateDataReader(query, CommandBehavior.Default))
            {
                StringBuilder sb = new StringBuilder();
                while (dr.Read())
                {
                    int j = 1;
                    for (; j < dr.FieldCount - 1; ++j)
                    {
                        if (dr[j].GetType() != CachedTypes.DBNull)
                        {
                            sb.Append(dr[j]);
                            sb.Append(" - ");
                        }
                    }
                    sb.Append(dr[j]);

                    ListItem item = new ListItem(sb.ToString(), dr[0].ToString());
                    base.Items.Add(item);

                    sb.Length = 0;
                }
            }
        }
 protected virtual void OnExecuteSqlComplete(SqlQuery query, DateTime executionStart, Exception executingException)
 {
     ExecuteSqlCompleteEventHandler fPtr = (ExecuteSqlCompleteEventHandler)this.events[DbAccess.ExecuteSqlCompleteEvent];
     if (fPtr != null)
     {
         ExecuteSqlCompleteEventArgs e = new ExecuteSqlCompleteEventArgs(this, query, executionStart, DateTime.Now, executingException);
         fPtr(e);
     }
 }
 protected virtual void OnPreExecuteSql(SqlQuery query)
 {
     PreExecuteSqlEventHandler fPtr = (PreExecuteSqlEventHandler)this.events[DbAccess.PreExecuteSqlEvent];
     if (fPtr != null)
     {
         PreExecuteSqlEventArgs e = new PreExecuteSqlEventArgs(this, query);
         fPtr(e);
     }
 }
        private DbCommand CreateCommand(SqlQuery query, out OutParameters outParameters)
        {
            if (null == query)
                throw new ArgumentNullException("query");

            string commandText = query.Text.ToString();
            if (String.IsNullOrEmpty(commandText))
                throw new ArgumentException("query, SqlQuery.Text is null");

            outParameters = null;

            this.OnPreExecuteSql(query);
            DbCommand cmd = null;
            try
            {
                cmd = this.connection.CreateCommand();

                foreach (SqlQueryParameter parameter in query.Parameters)
                {
                    DbParameter dbParameter = cmd.CreateParameter();
                    dbParameter.ParameterName = parameter.ParameterName;

                    dbParameter.IsNullable = parameter.IsNullable;

                    if (parameter.dbType.HasValue)
                        dbParameter.DbType = parameter.dbType.Value;

                    object parameterValue = parameter.Value;
                    dbParameter.Value = (null == parameterValue) ? DBNull.Value : parameterValue;

                    ParameterDirection direction = parameter.Direction;
                    dbParameter.Direction = direction;

                    cmd.Parameters.Add(dbParameter);

                    if (direction == ParameterDirection.InputOutput || direction == ParameterDirection.Output)
                    {
                        if (null == outParameters)
                            outParameters = new OutParameters();
                        outParameters.Add(parameter, dbParameter);
                    }
                }

                cmd.CommandText = commandText;
                cmd.CommandType = query.CmdType;
            }
            catch (Exception)
            {
                if (null != cmd) cmd.Dispose();
                throw;
            }

            this.OnCommandCreated(cmd);

            return cmd;
        }
        public virtual object ExecuteScalar(SqlQuery query)
        {
            if (null == query)
                throw new ArgumentNullException("query");

            OperationResult<Object> result = this.service.ExecuteScalar(query.Serialize());
            DbAccessProxy.TransferParameters(query.Parameters, result.CreateParameterList());

            return result.Value;
        }
        public virtual IDataReader CreateDataReader(SqlQuery query, CommandBehavior behavior)
        {
            if (null == query)
                throw new ArgumentNullException("query");

           OperationResult<DataTable> result =  this.service.CreateDataReader(query.Serialize(),behavior);
           DbAccessProxy.TransferParameters(query.Parameters, result.CreateParameterList());

           return result.Value.CreateDataReader();
        }
 public void Set(SqlQuery query)
 {
     if (!this.Value.IsNull() && null != query)
     {
         object value = this.cbx.SelectedValue.ConvertTo(this.DataType);
         if (null != value)//Çevirim İşlemi Başarılıysa
         {
             query.Parameters.Add(this.ParameterName, value);
         }
     }
 }
        private SqlQuery CreateSelectQuery()
        {
            char tableAlias = this.TableName[0];
            string tableNameOp = tableAlias + ".";

            string columnName;
            SqlQuery query = new SqlQuery();
            StringBuilder text = query.Text;
            text.Append("SELECT ");

            foreach (DbKey key in this.Keys)
            {
                columnName = key.ColumnName;

                text.Append(tableNameOp);
                text.Append(columnName);
                text.Append(" AS ");
                text.Append(columnName);
                text.Append(", ");
            }

            foreach(DbDefaultValue def in this.defaults)
            {
                columnName = def.ColumnName;

                text.Append(tableNameOp);
                text.Append(columnName);
                text.Append(" AS ");
                text.Append(columnName);
                text.Append(", ");
            }

            foreach (IEntityControl ctrl in this.Controls)
            {
                columnName = ctrl.PropertyName;

                text.Append(tableNameOp);
                text.Append(columnName);
                text.Append(" AS ");
                text.Append(columnName);
                text.Append(", ");
            }

            text.Remove(text.Length - 2, 1);

            text.Append("FROM ");
            text.Append(this.TableName);
            text.Append(' ');
            text.Append(tableAlias);

            return query;
        }
        //Upsert de Identity Parametre İçin Eklendi.
        public static SqlQueryParameter EnsureHasParameter(SqlQuery query, PropertyMetaData property, object entity)//inset de bu parametre normalde eklenmez ama upsert de update where de eklendiği için bu yapı kullanılıyor.
        {

            SqlQueryParameter identityParameter = query.Parameters.Find(property.ParameterName);
            if (null == identityParameter)
            {
                object parValue = property.Property.GetValue(entity, null);
                identityParameter = SqlQueryParameter.Create(property, parValue);

                query.Parameters.Add(identityParameter);
            }
            return identityParameter;
        }
        public virtual SqlQuery ToQuery()
        {
            string tableName = this.metaData.TableName;

            SqlQuery query = new SqlQuery();
            StringBuilder text = query.Text;
            text.Append("SELECT ");

            if (this.UseAlias)
            {
                char tableAlias = 'T';// tableName[0];
                string tableNameOp = tableAlias + ".";

                foreach (PropertyMetaData property in this.metaData.Properties)
                {
                    string columnName = property.Schema.ColumnName;

                    text.Append(tableNameOp);
                    text.Append(columnName);
                    text.Append(" AS ");
                    text.Append(columnName);
                    text.Append(", ");
                }
                text.Remove(text.Length - 2, 1);

                text.Append("FROM ");
                text.Append(tableName);
                text.Append(' ');
                text.Append(tableAlias);

                return query;
            }
            else
            {
                foreach (PropertyMetaData property in this.metaData.Properties)
                {
                    string columnName = property.Schema.ColumnName;

                    text.Append(columnName);
                    text.Append(", ");
                }
                text.Remove(text.Length - 2, 1);

                text.Append("FROM ");
                text.Append(tableName);
            }

            return query;
        }
        public virtual void SetColumnValue(SqlQuery query, PropertyMetaData metaData, object entity)//Parametewnin eklenip eklenmeyeceği bilinmdeğinden prefix ve entity verilmek zorunda.
        {
            SchemaInfo schema = metaData.Schema;
            PropertyInfo pi = metaData.Property;
            object parValue = metaData.Property.GetValue(entity, null);

            StringBuilder text = query.Text;
            if (schema.DefaultValue.Length != 0)
            {
                object defaultValue = ReflectionExtensions.GetDefault(pi.PropertyType);
                if (Object.Equals(defaultValue, parValue))//Eğer Property Değeri Default Haldeyse yazdır Bunu
                {
                    text.Append(schema.DefaultValue);
                    return;
                }
            }

            switch (schema.SqlValueType)
            {
                case SqlValueType.Parameterized:
                    text.Append(this.Prefix);
                    text.Append(metaData.ParameterName);

                    SqlQueryParameter par = SqlQueryParameter.Create(metaData, parValue);

                    query.Parameters.Add(par);
                    break;
                case SqlValueType.Text:
                    string textValue = null;
                    if (null != parValue)
                    {
                        Type dataType = metaData.Schema.DataType;//Neden Schema.DataType çünkü pi.PropertyType nullable olabalir.
                        if (WithQuotes.Contains(dataType))
                        {
                            textValue = "'" + parValue + "'";
                        }
                        else
                        {
                            IFormattable f = parValue as IFormattable;
                            textValue = null != f ? f.ToString(null, NumericCulture) : parValue.ToString();
                        }
                    }
                    text.Append(textValue);
                    break;
                default:
                    throw new NotSupportedException(schema.SqlValueType.ToString());
            }
        }
        //Arama Yapısından Sık Kullanılan İç Sorgular İçin Eklendi
        public static SqlQuery ToInnerQuery(this SqlQuery query, string alias)
        {
            if (null != query)
            {
                if (String.IsNullOrEmpty(alias))
                    alias = "T";

                SqlQuery inner = new SqlQuery();
                inner.Text.Append("SELECT * FROM (");
                inner.Combine(query);
                inner.Text.Append(") ");
                inner.Text.Append(alias);
                return inner;
            }
            return null;
        }
        public virtual SqlQuery CreateQuery(object entity, IEntityMetaData metaData)
        {
            if (null == entity)
                throw new ArgumentNullException("entity");

            SqlQueryHelper.IndexParameterNames(metaData, this.ParameterIndex);

            bool updatedFieldsEnabled = !this.UpdatedFields.IsEmptyList();

            SqlQuery query = new SqlQuery();
            StringBuilder text = query.Text;
            text.Append("UPDATE ");
            text.Append(metaData.TableName);
            text.Append(" SET ");

            foreach (PropertyMetaData property in metaData.Properties)
            {
                SchemaInfo schema = property.Schema;

                if (schema.IsKey)
                    continue;

                if (schema.DatabaseGeneratedOption != StoreGeneratedPattern.None)
                    continue;

                if (schema.ReadOnly)
                    continue;

                if (updatedFieldsEnabled && !this.UpdatedFields.Contains(schema.ColumnName))
                    continue;

                text.Append(schema.ColumnName);
                text.Append("=");

                SqlQueryHelper.SetColumnValue(ValueSetter.Instance, query, property, entity);

                text.Append(',');
            }
            text.Remove(text.Length - 1, 1);

            query.Combine(SqlQueryHelper.CreateWhereSqlByKeys(metaData, ':', entity));

            if (this.UseSemicolon)
                text.Append(';');

            return query;
        }
        private bool LoadDataSource()
        {
            if (this.IsAutoDataBindEnabled)
            {
                if (this.Key.Length == 0)
                    throw new InvalidOperationException("AutoDataBind is enabled but Key not be given");

                if (null == this.ItemsSource)
                {
                    SqlQuery query = new SqlQuery();

                    if (this.CustomSql.Length == 0)
                    {
                        StringBuilder text = query.Text;
                        text.Append("SELECT ");
                        foreach (GridColumn clmn in base.Columns)
                        {
                            GridBoundColumn boundColumn = clmn as GridBoundColumn;
                            if (null != boundColumn)
                            {
                                text.Append(boundColumn.DataField);
                                text.Append(" AS ");
                                text.Append(boundColumn.UniqueName);
                                text.Append(", ");
                            }
                        }
                        text.Remove(text.Length - 2, 1);
                        text.Append("FROM ");
                        text.Append(this.TableName);
                        if (this.ExtendedSql.Length != 0)
                        {
                            text.Append(' ');
                            text.Append(this.ExtendedSql);
                        }
                    }
                    else
                    {
                        query.Text.Append(this.CustomSql);
                    }

                    this.ItemsSource = this.dataAccess.QueryDataTable(query).DefaultView;
                }
                return true;
            }
            return false;
        }
        private void SetItemSource()
        {
            if (this.IsAutoDataBindEnabled)
            {
                SqlQuery query = new SqlQuery();
                StringBuilder text = query.Text;

                text.Append("SELECT ");
                text.Append(this.ListValueField);
                text.Append(',');
                text.Append(this.ListTextField);
                text.Append(" FROM ");
                text.Append(this.TableName);

                if (this.ExtendedSql.Length != 0)
                {
                    text.Append(' ');
                    text.Append(this.ExtendedSql);
                }

                this.ClearDataSource();

                if (this.AllowNull)
                {
                    this._itemSource.Add(ComboItem.Empty);
                }
                using (IDataReader dr = this.DataAccess.CreateDataReader(query, CommandBehavior.Default))
                {
                    while (dr.Read())
                    {
                        this._itemSource.Add(new ComboItem(dr[1].ToString(), dr[0].ToString()));
                    }
                }
            }
            else
                this.ClearDataSource();

            using (MemoryStream ms = new MemoryStream())
            {
                BinaryFormatter ser = new BinaryFormatter();
                ser.Serialize(ms, this._itemSource);
                ms.Position = 0;

                base.ViewState["ItemSource"] = Convert.ToBase64String(ms.ToArray());
            }
        }
        public int ExecuteNonQuery(SqlQuery query)
        {
            DbCommand cmd = null;
            DbTransaction tran = null;
            OutParameters outParameters;
            int ret = 0;
            DateTime executionStart = DateTime.Now;
            try
            {
                cmd = this.CreateCommand(query, out outParameters);

                if (this.enableTransaction)
                {
                    tran = this.connection.BeginTransaction();
                    cmd.Transaction = tran;
                }

                ret = cmd.ExecuteNonQuery();

                if (this.enableTransaction)
                    tran.Commit();
            }
            catch (Exception ex)
            {
                if (this.enableTransaction && tran != null)
                    tran.Rollback();

                this.OnExecuteSqlComplete(query, executionStart, ex);

                throw;
            }
            finally
            {
                if (this.enableTransaction) tran.Dispose();
                if (null != cmd) cmd.Dispose();
            }

            if (null != outParameters)
            {
                outParameters.SetOutParametersValues();
            }

            this.OnExecuteSqlComplete(query, executionStart, null);

            return ret;
        }
Exemple #23
0
        public void DataBind()
        {
            if (this.IsAutoDataBindingEnabled)
            {
                if (!String.IsNullOrEmpty(this.columnInfoList.TableName) && !String.IsNullOrEmpty(this.columnInfoList.KeyName))
                {
                    SqlQuery query = new SqlQuery();
                    StringBuilder text = query.Text;
                    text.Append("SELECT ");
                    text.Append(this.columnInfoList.KeyName);
                    text.Append(',');

                    foreach(GridColumnInfo info in this.columnInfoList)
                    {
                        text.Append(info.PropertyName);
                        text.Append(',');
                    }

                    text.Remove(text.Length - 1, 1);

                    text.Append(" FROM ");
                    text.Append(this.columnInfoList.TableName);

                    if (!String.IsNullOrEmpty(this.columnInfoList.FilterExpression))
                    {
                        text.Append(" WHERE ");
                        text.Append(this.columnInfoList.FilterExpression);
                    }
                    if (!String.IsNullOrEmpty(this.columnInfoList.SortExpression))
                    {
                        text.Append(" ORDER BY ");
                        text.Append(this.columnInfoList.SortExpression);
                    }

                    RecordTable table = new RecordTable(this.columnInfoList.TableName);
                    using(IDataReader dr = this.Factory.DataAccess.CreateDataReader(query, CommandBehavior.Default))
                    {
                        table.Load(dr, true, new UISchemaTableReader(this.columnInfoList.KeyName));
                    }

                    base.ItemsSource = table;
                }
            }
        }
        public virtual SqlQuery CreateQuery(object entity, IEntityMetaData metaData, out PropertyMetaData identity)
        {
            if (null == entity)
                throw new ArgumentNullException("entity");

            identity = null;

            SqlQueryHelper.IndexParameterNames(metaData, this.ParameterIndex);

            bool insertFieldsEnabled = !this.InsertFields.IsEmptyList();

            SqlQuery query = new SqlQuery();
            StringBuilder text = query.Text;
            text.Append("INSERT INTO ");
            text.Append(metaData.TableName);
            text.Append(" (");

            List<PropertyMetaData> validInfos = new List<PropertyMetaData>();
            foreach (PropertyMetaData property in metaData.Properties)
            {
                SchemaInfo schema = property.Schema;

                switch (schema.DatabaseGeneratedOption)
                {
                    case StoreGeneratedPattern.Identity:
                        if (null != identity)
                            throw new MultipleIdentityColumnFoundException(entity);

                        identity = property;
                        break;

                    case StoreGeneratedPattern.Computed:
                        break;

                    default:
                        if (insertFieldsEnabled && !this.InsertFields.Contains(schema.ColumnName))
                            continue;

                        text.Append(schema.ColumnName);
                        text.Append(',');

                        validInfos.Add(property);
                        break;
                }
            }

            text.Remove(text.Length - 1, 1);
            text.Append(") VALUES (");

            foreach (PropertyMetaData property in validInfos)
            {
                SchemaInfo schema = property.Schema;

                SqlQueryHelper.SetColumnValue(ValueSetter.Instance, query, property, entity);

                text.Append(',');
            }
            text.Remove(text.Length - 1, 1);
            text.Append(')');
            if (null != identity)
            {
                text.AppendLine();

                text.Append("SELECT @");
                text.Append(identity.ParameterName);
                text.Append("=SCOPE_IDENTITY()");

                SqlQueryParameter identityParameter = SqlQueryHelper.EnsureHasParameter(query, identity, entity);
                identityParameter.Direction = System.Data.ParameterDirection.InputOutput;
            }

            return query;
        }
        protected override int ExecuteInternal(IEnumerable<IEntityChange> changes, BatchCommandMode mode, IEntityMetaData metaData)
        {
            PropertyMetaData identity = null;
            Dictionary<string, object> outs = new Dictionary<string, object>();

            IEnumerable<IEntityChange> modified = changes.Where(e => e.State == EntityState.Modified);
            IEnumerable<IEntityChange> deleted = changes.Where(e => e.State == EntityState.Deleted);
            IEnumerable<IEntityChange> added = changes.Where(e => e.State == EntityState.Added);

            switch (mode)
            {
                case BatchCommandMode.Batch:

                    SqlQuery batchQuery = new SqlQuery();

                    batchQuery.Text.Append(GlobalInternal.SqlServerBeginStatement);
                    batchQuery.Text.AppendLine();

                    int index = 0;

                    if (!modified.IsEmptyList())
                    {
                        EntitySqlQueryBuilderUpdate updateBuilder = new EntitySqlQueryBuilderUpdate();
                        foreach (IEntityChange change in modified)
                        {
                            updateBuilder.ParameterIndex = index++;
                            updateBuilder.UpdatedFields = change.UpdatedFields;
                            batchQuery.Combine(updateBuilder.CreateQuery(change.Entity, metaData));
                            batchQuery.Text.AppendLine();
                        }
                        batchQuery.Text.AppendLine();
                    }

                    if (!deleted.IsEmptyList())
                    {
                        foreach (IEntityChange change in deleted)
                        {
                            SqlQuery deleteQuery = new SqlQuery();
                            deleteQuery.Text.Append("DELETE FROM ");
                            deleteQuery.Text.Append(metaData.TableName);

                            SqlQueryHelper.IndexParameterNames(metaData, index++);

                            deleteQuery.Combine(SqlQueryHelper.CreateWhereSqlByKeys(metaData, '@', change.Entity));

                            batchQuery.Combine(deleteQuery);
                            batchQuery.Text.AppendLine();
                        }
                        batchQuery.Text.AppendLine();
                    }

                    if (!added.IsEmptyList())
                    {
                        EntitySqlQueryBuilderInsert insertBuilder = new EntitySqlQueryBuilderInsert();
                        foreach (IEntityChange change in added)
                        {
                            insertBuilder.ParameterIndex = index++;
                            batchQuery.Combine(insertBuilder.CreateQuery(change.Entity, metaData, out identity));
                            if (null != identity)
                                outs.Add(identity.ParameterName, change.Entity);

                            batchQuery.Text.AppendLine();
                        }
                    }

                    batchQuery.Text.Append(GlobalInternal.SqlServerEndStatement);

                    int ret = base.DataAccess.ExecuteNonQuery(batchQuery);

                    if (null != identity)//outParameterNames.Count must be equal to entityList.Count.
                    {
                        foreach (KeyValuePair<string, object> kvp in outs)
                        {
                            string outParameterName = kvp.Key;
                            object identityValue = batchQuery.Parameters.Find(outParameterName).Value;
                            identity.Property.SetValue(kvp.Value, identityValue, null);
                        }
                    }

                    return ret;

                case BatchCommandMode.Single:
                    int sum = 0;

                    if (!modified.IsEmptyList())
                    {
                        EntityCommandUpdate updateCommand = new EntityCommandUpdate(base.DataAccess);
                        foreach (IEntityChange change in modified)
                        {
                            updateCommand.UpdatedFields = change.UpdatedFields;
                            sum += updateCommand.UpdateInternal(change.Entity, metaData);
                        }
                    }

                    if (!deleted.IsEmptyList())
                    {
                        EntityCommandDelete deleteCommand = new EntityCommandDelete(base.DataAccess);
                        foreach (IEntityChange change in deleted)
                        {
                            sum += deleteCommand.DeleteInternal(change.Entity, metaData);
                        }
                    }

                    if (!added.IsEmptyList())
                    {
                        EntityCommandInsert insertCommand = new EntityCommandInsert(base.DataAccess);
                        foreach (IEntityChange change in added)
                        {
                            sum += insertCommand.InsertInternal(change.Entity, metaData);
                        }
                    }

                    return sum;

                default:
                    throw new NotSupportedException(mode.ToString());
            }
        }
Exemple #26
0
 private void CreateDataSource(SqlQuery query)
 {
     this.table = new RecordTable();
     using (IDataReader dr = this.factory.DataAccess.CreateDataReader(query, System.Data.CommandBehavior.Default))
     {
         this.table.Load(dr, false, new UISchemaTableReader(this.ParentValueField));
     }
 }
        protected override int ExecuteInternal(IEnumerable<IEntityChange> changes, BatchCommandMode mode, IEntityMetaData metaData)
        {
            IEnumerable<IEntityChange> modified = changes.Where(e => e.State == EntityState.Modified);
            IEnumerable<IEntityChange> deleted = changes.Where(e => e.State == EntityState.Deleted);
            IEnumerable<IEntityChange> added = changes.Where(e => e.State == EntityState.Added);

            switch (mode)
            {
                case BatchCommandMode.Batch:

                    SqlQuery batchQuery = new SqlQuery();

                    batchQuery.Text.Append(GlobalInternal.BeginStatement);
                    batchQuery.Text.AppendLine();

                    int index = 0;

                    if (!modified.IsEmptyList())
                    {
                        EntitySqlQueryBuilderUpdate updateBuilder = new EntitySqlQueryBuilderUpdate() { UseSemicolon = true };
                        foreach (IEntityChange change in modified)
                        {
                            updateBuilder.ParameterIndex = index++;
                            updateBuilder.UpdatedFields = change.UpdatedFields;
                            batchQuery.Combine(updateBuilder.CreateQuery(change.Entity, metaData));
                            batchQuery.Text.AppendLine();
                        }
                        batchQuery.Text.AppendLine();
                    }

                    if (!deleted.IsEmptyList())
                    {
                        foreach (IEntityChange change in deleted)
                        {
                            SqlQuery deleteQuery = new SqlQuery();
                            deleteQuery.Text.Append("DELETE FROM ");
                            deleteQuery.Text.Append(metaData.TableName);

                            SqlQueryHelper.IndexParameterNames(metaData, index++);

                            deleteQuery.Combine(SqlQueryHelper.CreateWhereSqlByKeys(metaData, '@', change.Entity));

                            batchQuery.Combine(deleteQuery);
                            batchQuery.Text.AppendLine(";");
                        }
                        batchQuery.Text.AppendLine();
                    }

                    if (!added.IsEmptyList())
                    {
                        PropertyMetaData sequenceIdentity = null;
                        EntitySqlQueryBuilderInsert insertBuilder = new EntitySqlQueryBuilderInsert() { UseSemicolon = true };
                        foreach (IEntityChange change in added)
                        {
                            insertBuilder.ParameterIndex = index++;
                            batchQuery.Combine(insertBuilder.CreateQuery(change.Entity, metaData, out sequenceIdentity));

                            batchQuery.Text.AppendLine();
                        }
                    }

                    batchQuery.Text.Append(GlobalInternal.EndStatement);

                    return base.DataAccess.ExecuteNonQuery(batchQuery);

                case BatchCommandMode.Single:
                    int sum = 0;

                    if (!modified.IsEmptyList())
                    {
                        EntityCommandUpdate updateCommand = new EntityCommandUpdate(base.DataAccess);
                        foreach (IEntityChange change in modified)
                        {
                            updateCommand.UpdatedFields = change.UpdatedFields;
                            sum += updateCommand.UpdateInternal(change.Entity, metaData);
                        }
                    }

                    if (!deleted.IsEmptyList())
                    {
                        EntityCommandDelete deleteCommand = new EntityCommandDelete(base.DataAccess);
                        foreach (IEntityChange change in deleted)
                        {
                            sum += deleteCommand.DeleteInternal(change.Entity, metaData);
                        }
                    }

                    if (!added.IsEmptyList())
                    {
                        EntityCommandInsert insertCommand = new EntityCommandInsert(base.DataAccess);
                        foreach (IEntityChange change in added)
                        {
                            sum += insertCommand.InsertInternal(change.Entity, metaData);
                        }
                    }

                    return sum;

                default:
                    throw new NotSupportedException(mode.ToString());
            }
        }
 public static IEnumerable Query(this ICommandAdapter adapter, Type entityType, SqlQuery query)
 {
     if ((null != adapter && null != entityType) && null != query)
     {
         return QueryMethod(entityType).Invoke(adapter, new object[] { query }) as IEnumerable;
     }
     return null;
 }
 public static object QuerySingle(this ICommandAdapter adapter, Type entityType, SqlQuery query)
 {
     if ((null != adapter && null != entityType) && null != query)
     {
         return QuerySingleMethod(entityType).Invoke(adapter, new object[] { query });
     }
     return null;
 }
Exemple #30
0
 internal PreExecuteSqlEventArgs(DbAccess dataAccess, SqlQuery query)
 {
     this.dataAccess = dataAccess;
     this.query = query;
 }